1 package org.python.core; 2 3 import java.lang.reflect.Field ; 4 import java.lang.reflect.Modifier ; 5 6 public class PyFieldDescr extends PyDescriptor { 7 8 private Field field; 9 private Class field_type; 10 private boolean readonly; 11 12 public PyFieldDescr(String name, Class c, String field_name) { 13 this(name, c, field_name, false); 14 } 15 16 public PyFieldDescr( 17 String name, 18 Class c, 19 String field_name, 20 boolean readonly) { 21 this.name = name; 22 this.dtype = PyType.fromClass(c); 23 try { 24 field = c.getField(field_name); 25 } catch (NoSuchFieldException e) { 26 throw Py.SystemError("bogus attribute spec"); 27 } 28 int modifiers = field.getModifiers(); 29 if (Modifier.isStatic(modifiers)) { 30 throw Py.SystemError("static attributes not supported"); 31 } 32 this.readonly = readonly || Modifier.isFinal(modifiers); 33 field_type = field.getType(); 34 35 } 36 37 public String toString() { 38 return "<member '" + name + "' of '"+dtype.fastGetName()+"' objects>"; 39 } 40 41 44 public PyObject __get__(PyObject obj, PyObject type) { 45 try { 46 if (obj != null) { 47 PyType objtype = obj.getType(); 48 if (objtype != dtype && !objtype.isSubType(dtype)) 49 throw get_wrongtype(objtype); 50 return Py.java2py(field.get(obj)); 51 } 52 return this; 53 } catch (IllegalArgumentException e) { 54 throw Py.JavaError(e); 55 56 } catch (IllegalAccessException e) { 57 throw Py.JavaError(e); } 59 } 60 61 64 public void __set__(PyObject obj, PyObject value) { 65 try { 66 PyType objtype = obj.getType(); 68 if (objtype != dtype && !objtype.isSubType(dtype)) 69 throw get_wrongtype(objtype); 70 Object converted = value.__tojava__(field_type); 71 if (converted == Py.NoConversion) { 72 throw Py.TypeError(""); } 74 field.set(obj, converted); 75 } catch (IllegalArgumentException e) { 76 throw Py.JavaError(e); 77 } catch (IllegalAccessException e) { 78 throw Py.JavaError(e); } 80 } 81 82 85 public boolean implementsDescrSet() { 86 return !readonly; 87 } 88 89 92 public boolean isDataDescr() { 93 return true; 94 } 95 96 } 97 | Popular Tags |