-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathFieldAccessDemo.java
More file actions
40 lines (37 loc) · 1.03 KB
/
Copy pathFieldAccessDemo.java
File metadata and controls
40 lines (37 loc) · 1.03 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
import java.lang.reflect.Field;
public class FieldAccessDemo{
public static void main(String[] args){
Field f = null;
try{
Class<?> clazz = Class.forName("X");
X x = (X)clazz.newInstance();
f = clazz.getField("i");
System.out.println(f.getInt(x));
f.setInt(x, 20);
System.out.println(f.getInt(x));
f = clazz.getField("PI");
System.out.println(f.getDouble(null)); // The argument is ignored for static field, otherwise NullPointerException will be thrown out.
f.setDouble(x, 20); // It is not accessible with final modifier.
}catch(ClassNotFoundException cnfe){
cnfe.printStackTrace();
}catch(InstantiationException ie){
ie.printStackTrace();
}catch(NoSuchFieldException nsfe){
nsfe.printStackTrace();
}catch(IllegalAccessException iae){
iae.printStackTrace();
}finally{
try{
if(f!=null){
System.out.println(f.getDouble(null));
}
}catch(IllegalAccessException iae){
iae.printStackTrace();
}
}
}
}
class X{
public int i = 10;
public static final double PI = 3.14;
}