1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package io.netty.util.internal;
18
19 import java.util.HashMap;
20 import java.util.Map;
21
22 public abstract class TypeParameterMatcher {
23
24 private static final TypeParameterMatcher NOOP = new TypeParameterMatcher() {
25 @Override
26 public boolean match(Object msg) {
27 return true;
28 }
29 };
30
31 public static TypeParameterMatcher get(final Class<?> parameterType) {
32 final Map<Class<?>, TypeParameterMatcher> getCache =
33 InternalThreadLocalMap.get().typeParameterMatcherGetCache();
34
35 TypeParameterMatcher matcher = getCache.get(parameterType);
36 if (matcher == null) {
37 if (parameterType == Object.class) {
38 matcher = NOOP;
39 } else {
40 matcher = new ReflectiveMatcher(parameterType);
41 }
42 getCache.put(parameterType, matcher);
43 }
44
45 return matcher;
46 }
47
48 public static TypeParameterMatcher find(
49 final Object object, final Class<?> parametrizedSuperclass, final String typeParamName) {
50
51 final Map<Class<?>, Map<String, TypeParameterMatcher>> findCache =
52 InternalThreadLocalMap.get().typeParameterMatcherFindCache();
53 final Class<?> thisClass = object.getClass();
54
55 Map<String, TypeParameterMatcher> map = findCache.get(thisClass);
56 if (map == null) {
57 map = new HashMap<String, TypeParameterMatcher>();
58 findCache.put(thisClass, map);
59 }
60
61 TypeParameterMatcher matcher = map.get(typeParamName);
62 if (matcher == null) {
63 matcher = get(ReflectionUtil.resolveTypeParameter(object, parametrizedSuperclass, typeParamName));
64 map.put(typeParamName, matcher);
65 }
66
67 return matcher;
68 }
69
70 public abstract boolean match(Object msg);
71
72 private static final class ReflectiveMatcher extends TypeParameterMatcher {
73 private final Class<?> type;
74
75 ReflectiveMatcher(Class<?> type) {
76 this.type = type;
77 }
78
79 @Override
80 public boolean match(Object msg) {
81 return type.isInstance(msg);
82 }
83 }
84
85 TypeParameterMatcher() { }
86 }