-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathReflectTest.java
More file actions
44 lines (39 loc) · 1.47 KB
/
Copy pathReflectTest.java
File metadata and controls
44 lines (39 loc) · 1.47 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
package com.crow;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
/**
* Created by CrowHawk on 17/2/8.
*/
public class ReflectTest {
public static void main(String[] args) throws Exception{
FieldReflect fr = refConstructor(1,2);
System.out.println(fr.toString());
refFieldChange(fr, "a");
System.out.println("fr.a = " + fr.a);
refFieldChange(fr, "str1");
System.out.println("fr.str1 = " + fr.str1);
}
public static FieldReflect refConstructor(int a, int b) throws Exception{//使用反射构造器创建对象
Class[] paralist = {int.class, int.class};
Constructor cons = FieldReflect.class.getDeclaredConstructor(paralist);
FieldReflect fr = (FieldReflect) cons.newInstance(a, b);
return fr;
}
public static void refFieldChange(FieldReflect fr, String fieldName) throws Exception{
//使用Field类改变类的实例域,如果是int型,全部设为3,如果是String类型,将String中的"b"改为"c"
Field field = fr.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
if(field.getType() == int.class){
field.set(fr, 3);
}
else if(field.getType() == String.class) {
String string = (String) field.get(fr);
string.replace("b", "c");
field.set(fr, string);
}
else {
throw new IOException();
}
}
}