Code sample

Due to the nature of Java generic erasure, when we use the generic Class, we cannot directly know the type of the generic T. At this time can use the Class in the Java reflection. GetGenericSuperclass () to get to the subclass type used by the real concrete realization

public class TypeParent<T, R> { private Class<T> mTClass; private Class<R> mRClass; @SuppressWarnings("unchecked") public TypeParent() { Type t = getClass().getGenericSuperclass(); System.out.println("getClass() == " + getClass()); System.out.println("getClass().getSuperclass() == " + getClass().getSuperclass()); System.out.println("getClass().getGenericSuperclass() == " + t); Type firType = ((ParameterizedType) t).getActualTypeArguments()[0]; System.out.println("((ParameterizedType) t).getActualTypeArguments()[0] == " + firType); Type secType = ((ParameterizedType) t).getActualTypeArguments()[1]; System.out.println("((ParameterizedType) t).getActualTypeArguments()[1] == " + secType); try { mTClass = (Class<T>) firType; mRClass = (Class<R>) secType; } catch (ClassCastException e) { e.printStackTrace(); } System.out.println("getActualTypeArguments() length == " + ((ParameterizedType) t).getActualTypeArguments().length); }}Copy the code

At this point TypeParent declares the generic types T and R for the generic classes

The subclass implementation

public class TypeSub extends TypeParent<Integer, String> {} public class Main { public static void main(String[] args) { new TypeClass(); }}Copy the code

Running results:

getClass() == class TypeClass getClass().getSuperclass() == class TypeParent getClass().getGenericSuperclass() == TypeParent<java.lang.Integer, java.lang.String> ((ParameterizedType) t).getActualTypeArguments()[0] == class java.lang.Integer ((ParameterizedType) t).getActualTypeArguments()[1] == class java.lang.String

mTClass == class java.lang.Integer

mRClass == class java.lang.String

getActualTypeArguments() length == 2

parsing

Type getGenericSuperclass()

Returns the Type class of the parent of the current Type. ParameterizedType is returned if the parent Class is generic; Class is returned otherwise

Type[] getActualTypeArguments()

Returns the Type class corresponding to the parameter in the generic class <>. From this we can convert the Type Type we get from getActualTypeArguments() to the Class Type of the generic Type