package com.monkeylessey.sys.domain.base;
|
|
import java.lang.reflect.ParameterizedType;
|
import java.lang.reflect.Type;
|
|
/**
|
* 用于获取泛型,因为泛型方法无法传入:List<String>.class 这样的Class,而泛型类可以,所以通过反射就能拿到
|
*
|
* @author 29443
|
*/
|
public abstract class TypeReference<T> {
|
private final Type type;
|
|
protected TypeReference() {
|
Class<?> parameterizedTypeReferenceSubclass = findParameterizedTypeReferenceSubclass(this.getClass());
|
Type type = parameterizedTypeReferenceSubclass.getGenericSuperclass();
|
ParameterizedType parameterizedType = (ParameterizedType) type;
|
this.type = parameterizedType.getActualTypeArguments()[0];
|
}
|
|
public Type getType() {
|
return this.type;
|
}
|
|
@Override
|
public boolean equals(Object obj) {
|
return this == obj || obj instanceof TypeReference && this.type.equals(((TypeReference) obj).type);
|
}
|
|
@Override
|
public int hashCode() {
|
return this.type.hashCode();
|
}
|
|
@Override
|
public String toString() {
|
return "TypeReference<" + this.type + ">";
|
}
|
|
private static Class<?> findParameterizedTypeReferenceSubclass(Class<?> child) {
|
Class<?> parent = child.getSuperclass();
|
if (Object.class == parent) {
|
throw new IllegalStateException("Expected TypeReference superclass");
|
} else {
|
// 递归找到直接继承TypeReference抽象类的Class
|
return TypeReference.class == parent ? child : findParameterizedTypeReferenceSubclass(parent);
|
}
|
}
|
}
|