-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReflectionDemo.java
More file actions
53 lines (45 loc) · 1.98 KB
/
ReflectionDemo.java
File metadata and controls
53 lines (45 loc) · 1.98 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
package com.loon.reflection;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Created with IntelliJ IDEA.
* User: Loon
* Date: 13-3-31
* Time: 下午3:25
* To change this template use File | Settings | File Templates.
*/
public class ReflectionDemo {
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException, ClassNotFoundException, InstantiationException {
Class cls = Class.forName("com.loon.reflection.Dog");
Object dog = cls.newInstance();
Method[] superMethods = null;
if (cls.getGenericSuperclass() != null) {
Class superClass = cls.getSuperclass();
superMethods = superClass.getDeclaredMethods();
Method setAge = superClass.getDeclaredMethod("setAge", int.class);
Method setGender = superClass.getDeclaredMethod("setGender", String.class);
setAge.invoke(dog, 1);
setGender.invoke(dog, "male");
}
Method[] methods = cls.getDeclaredMethods();
Method[] allMethods = new Method[methods.length+superMethods.length];
System.arraycopy(methods, 0, allMethods, 0, methods.length);
System.arraycopy(superMethods, 0, allMethods, methods.length, superMethods.length);
for (Method method : allMethods) {
if (method.getName().startsWith("get")) {
Object value = method.invoke(dog);
System.out.println(method.getName() +" == "+value);
}
}
Method setFoot = cls.getDeclaredMethod("setFoot", int.class);
setFoot.invoke(dog, 4);
Method getFoot = cls.getDeclaredMethod("getFoot");
System.out.println(getFoot.invoke(dog));
Field foot = cls.getDeclaredField("foot");
// set Field public
foot.setAccessible(true);
foot.set(dog, 8);
System.out.println(getFoot.invoke(dog));
}
}