Repository navigation
Expand file tree
/
Copy pathReflectTest.java
More file actions
72 lines (51 loc) · 2 KB
/
Copy pathReflectTest.java
File metadata and controls
72 lines (51 loc) · 2 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/**
*
*/
package com.test.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import com.test.web.dao.impl.UserDaoImpl2;
import com.test.web.model.User;
/**
* @author aubrey
* @date 上午10:48:00
*
*/
public class ReflectTest {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
Class clazz = UserDaoImpl2.class;
Class clazz2 = new UserDaoImpl2().getClass();
Class clazz3 = ReflectTest.class.getClassLoader().loadClass("com.test.web.dao.impl.UserDaoImpl2");
System.out.println("=====属性=======");
Field[] fields = clazz.getFields();
Field[] fields2 = clazz.getDeclaredFields();
for(Field f : fields) {
System.out.println("name:" + f.getName() + ";type:" + f.getType());
}
System.out.println("====declared=====");
for(Field f : fields2) {
System.out.println("name:" + f.getName() + ";type:" + f.getType());
}
System.out.println("=====方法=======");
Method[] methods = clazz.getDeclaredMethods();
for(Method m : methods) {
System.out.println(m.getName());
}
Method method = clazz.getDeclaredMethod("insert", User.class);
//无参数构造
UserDaoImpl2 userDao2 = (UserDaoImpl2) clazz.newInstance();
//有参数构造
Constructor constructor = clazz.getConstructor(String.class);
UserDaoImpl2 userDao3 = (UserDaoImpl2) constructor.newInstance("test属性");
System.out.println("userDao3" + userDao3);
System.out.println("==invoke:======");
method.invoke(userDao2,new User());
// userDao2.insert(new User());
System.out.println("结束");
}
public static Object getInstance(Class clazz) throws InstantiationException, IllegalAccessException {
return clazz.newInstance();
}
}