01: package org.python.core;
02:
03: import java.lang.reflect.Field;
04: import java.lang.reflect.Modifier;
05:
06: public class PyFieldDescr extends PyDescriptor {
07:
08: private Field field;
09: 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(String name, Class c, String field_name,
17: boolean readonly) {
18: this .name = name;
19: this .dtype = PyType.fromClass(c);
20: try {
21: field = c.getField(field_name);
22: } catch (NoSuchFieldException e) {
23: throw Py.SystemError("bogus attribute spec");
24: }
25: int modifiers = field.getModifiers();
26: if (Modifier.isStatic(modifiers)) {
27: throw Py.SystemError("static attributes not supported");
28: }
29: this .readonly = readonly || Modifier.isFinal(modifiers);
30: field_type = field.getType();
31:
32: }
33:
34: public String toString() {
35: return "<member '" + name + "' of '" + dtype.fastGetName()
36: + "' objects>";
37: }
38:
39: /**
40: * @see org.python.core.PyObject#__get__(org.python.core.PyObject, org.python.core.PyObject)
41: */
42: public PyObject __get__(PyObject obj, PyObject type) {
43: try {
44: if (obj != null) {
45: PyType objtype = obj.getType();
46: if (objtype != dtype && !objtype.isSubType(dtype))
47: throw get_wrongtype(objtype);
48: return Py.java2py(field.get(obj));
49: }
50: return this ;
51: } catch (IllegalArgumentException e) {
52: throw Py.JavaError(e);
53:
54: } catch (IllegalAccessException e) {
55: throw Py.JavaError(e); // unexpected
56: }
57: }
58:
59: /**
60: * @see org.python.core.PyObject#__set__(org.python.core.PyObject, org.python.core.PyObject)
61: */
62: public void __set__(PyObject obj, PyObject value) {
63: try {
64: // obj != null
65: PyType objtype = obj.getType();
66: if (objtype != dtype && !objtype.isSubType(dtype))
67: throw get_wrongtype(objtype);
68: Object converted = value.__tojava__(field_type);
69: if (converted == Py.NoConversion) {
70: throw Py.TypeError(""); // xxx
71: }
72: field.set(obj, converted);
73: } catch (IllegalArgumentException e) {
74: throw Py.JavaError(e);
75: } catch (IllegalAccessException e) {
76: throw Py.JavaError(e); // unexpected
77: }
78: }
79:
80: /**
81: * @see org.python.core.PyObject#implementsDescrSet()
82: */
83: public boolean implements DescrSet() {
84: return !readonly;
85: }
86:
87: /**
88: * @see org.python.core.PyObject#isDataDescr()
89: */
90: public boolean isDataDescr() {
91: return true;
92: }
93:
94: }
|