If you want to get the generic (generic class) parameter type T, you might use the following code:
Class<t> Tclass = (class<t>) ((Parameterizedtype) GetClass (). Getgenericsuperclass ())
. Getactualtypearguments () [0];
Gets the actual generic parameter type of the immediate base class of the current class (you are new);
However, you may encounter the following two exceptions:
1.java.lang.classcastexception:libcore.reflect.typevariableimpl
cannot is cast to Java.lang.Class
2. Java.lang.ClassCastException:java.lang.Class
cannot be cast to Java.lang.reflect.ParameterizedType
The new object is not a generic, and converting to Parameterizedtype will throw an exception 2, Getactualtypearguments (), to get the actual incoming type, then the actual type T needs to be passed to this class;
If you want to get the actual type, you should do this: the anonymous inner class of the new generic class, as follows:
Class Atest<t> {public
atest () {
class<t> T = (class<t>) (Parameterizedtype) GetClass (). Getgenericsuperclass ())
. getactualtypearguments () [0];
LOG.I ("T is:" + t);
}
Call new Atest<string> () {};
Result: T Is:class java.lang.String
If {} is omitted, the direct base class of atest is the object
The following code:
Class Atest<t> {public
atest () {
log.i ("atest");
}
Class Btest<t> extends Atest<t> {public
btest () {
. getactualtypearguments () [0];
LOG.I ("T is:" + t);
}
New Btest<string> ();
So called Getgenericsuperclass () gets the atest, which is the Parameterizedtype type, but because the actual type passed in the Btest,atest parameter is T, not the actual type, will report an exception 1
The correct approach is new btest<string> () {};