1 package nl.tudelft.simulation.introspection.fields;
2
3 import java.lang.reflect.Field;
4
5 import nl.tudelft.simulation.introspection.AbstractProperty;
6 import nl.tudelft.simulation.introspection.Property;
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 public class FieldProperty extends AbstractProperty implements Property
22 {
23
24 private Object owner = null;
25
26
27 private Field descriptor = null;
28
29
30 private boolean editable = false;
31
32
33
34
35
36
37
38 public FieldProperty(final Object owner, final Field descriptor, final boolean editable)
39 {
40
41 this.owner = owner;
42 this.descriptor = descriptor;
43 this.descriptor.setAccessible(true);
44 this.editable = editable;
45 }
46
47
48
49
50
51
52 public FieldProperty(final Object owner, final Field descriptor)
53 {
54 this(owner, descriptor, true);
55 }
56
57 @Override
58 public String getName()
59 {
60 return this.descriptor.getName();
61 }
62
63 @Override
64 public Class<?> getType()
65 {
66 return this.descriptor.getType();
67 }
68
69 @Override
70 public void setRegularValue(final Object value)
71 {
72 Class<?> type = this.descriptor.getType();
73 if (!type.isInstance(value) || !this.editable)
74 { throw new IllegalArgumentException("Cannot assign " + value + " to " + this.owner + ", " + this.descriptor); }
75 synchronized (this.owner)
76 {
77 try
78 {
79 this.descriptor.set(this.owner, value);
80 }
81 catch (Exception exception)
82 {
83 throw new IllegalArgumentException(this + " - setRegularValue", exception);
84 }
85 }
86 }
87
88 @Override
89 public Object getValue()
90 {
91 try
92 {
93 return this.descriptor.get(this.owner);
94 }
95 catch (Exception exception)
96 {
97 throw new IllegalArgumentException(this + " - getValue", exception);
98 }
99 }
100
101 @Override
102 public Object getInstance()
103 {
104 return this.owner;
105 }
106
107 @Override
108 public boolean isEditable()
109 {
110 return this.editable;
111 }
112 }