forked from storytellersoftware/java-httpserver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReflectionTest.java
More file actions
83 lines (66 loc) · 2.21 KB
/
ReflectionTest.java
File metadata and controls
83 lines (66 loc) · 2.21 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
80
81
82
83
package tests;
import httpserver.HTTPHandler;
import httpserver.HTTPRequest;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.junit.Test;
public class ReflectionTest {
@Test
public void getAllMethods() {
Class<? extends HTTPHandler> c = HandlerTest.class;
List<Method> hellos = getMethodsByName(c, "sayHello");
List<Class<? extends Object>> parameterTypes = new ArrayList<>();
parameterTypes.add(String.class);
// find our method
outer:
for (Method m : new ArrayList<Method>(hellos)) {
// determine if this method takes all parameters of this path
Class<? extends Object>[] reqParams = m.getParameterTypes();
// does it have enough parameters?
if (reqParams.length < parameterTypes.size() + 1 ||
reqParams.length > parameterTypes.size() + 3) {
hellos.remove(m);
continue;
}
// going backwards, make sure all parameters match
for (int i = 1; i <= parameterTypes.size(); i++) {
// i goes up because inParams and parameterTypes will have different
// lengths.
Class<?> inClass = parameterTypes.get(parameterTypes.size() - i);
Class<?> reqClass = reqParams[reqParams.length - i];
if (!inClass.equals(reqClass)) {
hellos.remove(m);
continue outer;
}
}
if (reqParams.length > parameterTypes.size() + 1) {
// is second param HTTPRequest?
if (reqParams[1].equals(HTTPRequest.class)) {
if (reqParams.length == parameterTypes.size() + 3 &&
!reqParams[2].equals(Map.class)) {
hellos.remove(m);
continue;
}
}
else if (!reqParams[1].equals(Map.class)) {
hellos.remove(m);
continue;
}
}
}
for (Method m : hellos) {
System.out.println(m.toGenericString());
}
}
public static List<Method> getMethodsByName(Class<?> c, String name) {
List<Method> out = new ArrayList<>();
for (Method m: c.getMethods()) {
if (m.getName().equals(name)) {
out.add(m);
}
}
return out;
}
}