-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClassRef.java
More file actions
30 lines (27 loc) · 830 Bytes
/
Copy pathClassRef.java
File metadata and controls
30 lines (27 loc) · 830 Bytes
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
package ReflectClass;
/**
* 获取Class对象
*/
public class ClassRef {
public static void main(String[] args) {
//1、通过Class类的forName获取
try {
Class<?> clazz = Class.forName("ReflectClass.ClassRef");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//2、直接获取
Class<?> clazz = ClassRef.class;
//3、getClass()方法
clazz = new ClassRef().getClass();
//通过Class的newInstance创建对象,只能调用默认构造器
try {
Object o = clazz.newInstance();
System.out.println(o);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}