1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.util;
20
21 import static org.junit.Assert.assertTrue;
22
23 import java.lang.reflect.Method;
24 import java.lang.reflect.Modifier;
25 import java.util.HashMap;
26 import java.util.HashSet;
27 import java.util.Map;
28 import java.util.Set;
29
30
31
32
33
34
35
36
37 public class BuilderStyleTest {
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57 @SuppressWarnings("rawtypes")
58 public static void assertClassesAreBuilderStyle(Class... classes) {
59 for (Class clazz : classes) {
60 System.out.println("Checking " + clazz);
61 Method[] methods = clazz.getDeclaredMethods();
62 Map<String, Set<Method>> methodsBySignature = new HashMap<>();
63 for (Method method : methods) {
64 if (!Modifier.isPublic(method.getModifiers())) {
65 continue;
66 }
67 Class<?> ret = method.getReturnType();
68 if (method.getName().startsWith("set") || method.getName().startsWith("add")) {
69 System.out.println(" " + clazz.getSimpleName() + "." + method.getName() + "() : "
70 + ret.getSimpleName());
71
72
73
74
75
76
77 String sig = method.getName();
78 for (Class<?> param : method.getParameterTypes()) {
79 sig += param.getName();
80 }
81 Set<Method> sigMethods = methodsBySignature.get(sig);
82 if (sigMethods == null) {
83 sigMethods = new HashSet<Method>();
84 methodsBySignature.put(sig, sigMethods);
85 }
86 sigMethods.add(method);
87 }
88 }
89
90 for (Map.Entry<String, Set<Method>> e : methodsBySignature.entrySet()) {
91
92 boolean found = false;
93 for (Method m : e.getValue()) {
94 found = clazz.isAssignableFrom(m.getReturnType());
95 if (found) break;
96 }
97 String errorMsg = "All setXXX()|addXX() methods in " + clazz.getSimpleName()
98 + " should return a " + clazz.getSimpleName() + " object in builder style. "
99 + "Offending method:" + e.getValue().iterator().next().getName();
100 assertTrue(errorMsg, found);
101 }
102 }
103 }
104 }