forked from EB-wilson/JavaDynamilizer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJavaVariable.java
More file actions
58 lines (49 loc) · 1.32 KB
/
Copy pathJavaVariable.java
File metadata and controls
58 lines (49 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package dynamilize;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
@SuppressWarnings("unchecked")
public class JavaVariable implements IVariable{
private final Field field;
private final MethodHandle setter;
private final MethodHandle getter;
public JavaVariable(Field field){
this.field = field;
MethodHandles.Lookup lookup = MethodHandles.lookup();
try{
getter = lookup.unreflectGetter(field);
setter = isConst()? null: lookup.unreflectSetter(field);
}catch(IllegalAccessException e){
throw new IllegalHandleException(e);
}
}
@Override
public String name(){
return field.getName();
}
@Override
public boolean isConst(){
return Modifier.isFinal(field.getModifiers());
}
@Override
public <T> T get(DynamicObject<?> obj){
try{
return (T) getter.invoke(obj);
}catch(ClassCastException e){
throw e;
}catch(Throwable e){
throw new IllegalHandleException(e);
}
}
@Override
public void set(DynamicObject<?> obj, Object value){
if(isConst())
throw new IllegalHandleException("can not modifier a const variable");
try{
setter.invoke(obj, value);
}catch(Throwable e){
throw new IllegalHandleException(e);
}
}
}