forked from AndrewProgramming/JavaTutorialCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTest07.java
More file actions
79 lines (50 loc) · 2.01 KB
/
Test07.java
File metadata and controls
79 lines (50 loc) · 2.01 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
73
74
75
76
77
78
79
package reflection;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test07 {
public static void main(String[] args)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
//普通的方式来创建对象
test01();
//反射的方式来创建对象,不关闭安全监测机制
test02();
//反射的方式来创建对象,关闭安全监测机制
test03();
}
public static void test01() {
User user = new User();
long startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
user.getName();
}
long endTime = System.currentTimeMillis();
System.out.println("普通方式执行10亿次:" + (endTime - startTime) + "ms");
}
//反射的方式来创建对象,不关闭安全监测机制
public static void test02()
throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
User user = new User();
Class c1 = user.getClass();
Method getName = c1.getDeclaredMethod("getName", null);
long startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
getName.invoke(user, null);
}
long endTime = System.currentTimeMillis();
System.out.println("反射的方式来创建对象,不关闭安全监测机制:" + (endTime - startTime) + "ms");
}
//反射的方式来创建对象,关闭安全监测机制
public static void test03()
throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
User user = new User();
Class c1 = user.getClass();
Method getName = c1.getDeclaredMethod("getName", null);
getName.setAccessible(true);
long startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
getName.invoke(user, null);
}
long endTime = System.currentTimeMillis();
System.out.println("反射的方式来创建对象,关闭安全监测机制:" + (endTime - startTime) + "ms");
}
}