-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConstructorRef.java
More file actions
63 lines (55 loc) · 1.85 KB
/
Copy pathConstructorRef.java
File metadata and controls
63 lines (55 loc) · 1.85 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
package ReflectClass;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/**
* Class的构造器对象
*/
public class ConstructorRef {
public ConstructorRef() {
}
private ConstructorRef(String name) {
}
public static void main(String[] args) {
Class<?> c = ConstructorRef.class;
//所有"公有的"构造方法
Constructor[] constructors = c.getConstructors();
for (Constructor constructor : constructors) {
System.out.println(constructor);
}
System.out.println("-----");
//获取所有构造方法,包括私有
constructors = c.getDeclaredConstructors();
for (Constructor constructor : constructors) {
System.out.println(constructor);
}
System.out.println("-----");
//根据参数获取 单个 公有
Constructor con = null;
try {
con = c.getConstructor(String.class);
System.out.println(con);
} catch (NoSuchMethodException e) {
System.out.println("Couldn't find ..");
}
System.out.println("-----");
//根据参数获取 单个 从所有的构造方法中找
try {
con = c.getDeclaredConstructor(String.class);
System.out.println(con);
} catch (NoSuchMethodException e) {
System.out.println("Couldn't find ..");
}
System.out.println("--");
//构造器可以用来创建对象
try {
Object o=con.newInstance("name");
System.out.println(o.getClass());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}