forked from json-iterator/java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTypeLiteral.java
More file actions
79 lines (69 loc) · 2.95 KB
/
TypeLiteral.java
File metadata and controls
79 lines (69 loc) · 2.95 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 com.jsoniter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public class TypeLiteral<T> {
final Type type;
final String cacheKey;
/**
* Constructs a new type literal. Derives represented class from type parameter.
* Clients create an empty anonymous subclass. Doing so embeds the type parameter in the
* anonymous class's type hierarchy so we can reconstitute it at runtime despite erasure.
*/
@SuppressWarnings("unchecked")
protected TypeLiteral() {
this.type = getSuperclassTypeParameter(getClass());
cacheKey = generateCacheKey(type);
}
public static String generateCacheKey(Type type) {
StringBuilder decoderClassName = new StringBuilder("codegen.");
if (type instanceof Class) {
Class clazz = (Class) type;
if (clazz.isAnonymousClass()) {
throw new RuntimeException("anonymous class not supported: " + clazz);
}
decoderClassName.append(clazz.getCanonicalName().replace("[]", "_array"));
} else if (type instanceof ParameterizedType) {
ParameterizedType pType = (ParameterizedType) type;
Class clazz = (Class) pType.getRawType();
decoderClassName.append(clazz.getCanonicalName().replace("[]", "_array"));
for (int i = 0; i < pType.getActualTypeArguments().length; i++) {
String typeName = formatTypeWithoutSpecialCharacter(pType.getActualTypeArguments()[i]);
decoderClassName.append('_');
decoderClassName.append(typeName);
}
} else {
throw new UnsupportedOperationException("do not know how to handle: " + type);
}
return decoderClassName.toString().replace("$", "_");
}
private static String formatTypeWithoutSpecialCharacter(Type type) {
if (type instanceof Class) {
Class clazz = (Class) type;
return clazz.getCanonicalName();
}
if (type instanceof ParameterizedType) {
ParameterizedType pType = (ParameterizedType) type;
String typeName = formatTypeWithoutSpecialCharacter(pType.getRawType());
for (Type typeArg : pType.getActualTypeArguments()) {
typeName += "_";
typeName += formatTypeWithoutSpecialCharacter(typeArg);
}
return typeName;
}
throw new RuntimeException("unsupported type: " + type);
}
static Type getSuperclassTypeParameter(Class<?> subclass) {
Type superclass = subclass.getGenericSuperclass();
if (superclass instanceof Class) {
throw new RuntimeException("Missing type parameter.");
}
ParameterizedType parameterized = (ParameterizedType) superclass;
return parameterized.getActualTypeArguments()[0];
}
public Type getType() {
return type;
}
public String getCacheKey() {
return cacheKey;
}
}