1 package org.python.core; 2 3 import java.lang.reflect.InvocationTargetException ; 4 import java.lang.reflect.Method ; 5 import java.lang.reflect.Modifier ; 6 7 public class PyGetSetDescr extends PyDescriptor { 8 9 private Method get_meth; 10 private Method set_meth; 11 private Class getset_type; 12 13 public PyGetSetDescr(PyType dtype, String name, Class c, String get, String set) { 14 this.name = name; 15 this.dtype = dtype; 16 try { 17 get_meth = c.getMethod(get, new Class [] { 18 }); 19 } catch (NoSuchMethodException e) { 20 throw Py.SystemError("bogus getset spec"); 21 } 22 if (Modifier.isStatic(get_meth.getModifiers())) 23 throw Py.SystemError("static getset not supported"); 24 getset_type = get_meth.getReturnType(); 25 if (set != null) { 26 try { 27 set_meth = c.getMethod(set, new Class [] { getset_type }); 28 } catch (NoSuchMethodException e) { 29 throw Py.SystemError("bogus getset spec"); 30 } 31 if (Modifier.isStatic(set_meth.getModifiers())) 32 throw Py.SystemError("static getset not supported"); 33 34 } 35 } 36 37 public PyGetSetDescr(String name, Class c, String get, String set) { 38 this(PyType.fromClass(c),name,c,get,set); 39 } 40 41 public String toString() { 42 return "<attribute '"+name+"' of '"+dtype.fastGetName()+"' objects>"; 43 } 44 45 46 49 public PyObject __get__(PyObject obj, PyObject type) { 50 try { 51 if (obj != null) { 52 PyType objtype = obj.getType(); 53 if (objtype != dtype && !objtype.isSubType(dtype)) 54 throw get_wrongtype(objtype); 55 Object v = get_meth.invoke(obj, new Object [0]); 56 if (v == null) { 57 obj.noAttributeError(name); 58 } 59 return Py.java2py(v); 60 } 61 return this; 62 } catch (IllegalArgumentException e) { 63 throw Py.JavaError(e); 64 } catch (IllegalAccessException e) { 65 throw Py.JavaError(e); } catch (InvocationTargetException e) { 67 throw Py.JavaError(e); 68 } 69 } 70 71 74 public void __set__(PyObject obj, PyObject value) { 75 try { 76 PyType objtype = obj.getType(); 78 if (objtype != dtype && !objtype.isSubType(dtype)) 79 throw get_wrongtype(objtype); 80 Object converted = value.__tojava__(getset_type); 81 if (converted == Py.NoConversion) { 82 throw Py.TypeError(""); } 84 set_meth.invoke(obj, new Object [] { converted }); 85 86 } catch (IllegalArgumentException e) { 87 throw Py.JavaError(e); 88 } catch (IllegalAccessException e) { 89 throw Py.JavaError(e); } catch (InvocationTargetException e) { 91 throw Py.JavaError(e); 92 } 93 } 94 95 98 public boolean implementsDescrSet() { 99 return set_meth != null; 100 } 101 102 105 public boolean isDataDescr() { 106 return true; 107 } 108 109 } 110 | Popular Tags |