-
Notifications
You must be signed in to change notification settings - Fork 1
/
MethodSearchWaysCompare.java
72 lines (56 loc) · 2.27 KB
/
MethodSearchWaysCompare.java
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 org.n3r.sandbox.seckill;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.io.IOException;
import java.lang.reflect.Method;
public class MethodSearchWaysCompare {
public static boolean findMethodInClassByException(Class<?> aClass, Method method) {
try {
aClass.getMethod(method.getName(), method.getParameterTypes());
return true;
} catch (NoSuchMethodException e) {
return false;
}
}
public static boolean findMethodInClassBySearch(Class<?> aClass, Method method) {
for (Method aMethod : aClass.getMethods()) {
if (aMethod.getName().equals(method.getName())
&& sameParameterTypes(aMethod.getParameterTypes(), method.getParameterTypes())) {
return true;
}
}
return false;
}
private static boolean sameParameterTypes(Class<?>[] parameterTypes1, Class<?>[] parameterTypes2) {
if (parameterTypes1.length != parameterTypes2.length) return false;
for (int i = 0; i < parameterTypes1.length; ++i) {
if (parameterTypes1[i] != parameterTypes2[i]) return false;
}
return true;
}
@Benchmark
public void methodNotFoundException() throws Exception {
Class<?> aClass = Object.class;
Method aMethod = MethodSearchWaysCompare.class.getMethod("methodNotFoundException");
findMethodInClassByException(aClass, aMethod);
}
@Benchmark
public void methodsSearch() throws Exception {
Class<?> aClass = Object.class;
Method aMethod = MethodSearchWaysCompare.class.getMethod("methodNotFoundException");
findMethodInClassBySearch(aClass, aMethod);
}
public static void main(String[] args) throws RunnerException, IOException {
Options opt = new OptionsBuilder()
.include(MethodSearchWaysCompare.class.getSimpleName())
.warmupIterations(1)
.threads(1)
.measurementIterations(10)
.forks(0)
.build();
new Runner(opt).run();
}
}