Reprint please indicate the source:
http://blog.csdn.net/sinat_15877283/article/details/50971262;
This article comes from: "Winledon's Blog"
Generics are often used in our framing frameworks, and we know that generics have the benefit of checking type safety at compile time, and that all casts are automatic and implicit, with a high rate of reuse of code,
However, sometimes <method> 's parameters are not directly coerced into generic types, such as the following code:
It is obvious that the string type cannot be cast to <T>
Then we'll need to use Fastjson or Gson this type of conversion tool for type conversion work
But the Fastjson and Gson methods are as follows:
public static <T> T parseobject (String text, class<t> clazz) {return
parseobject (text, clazz, new Feature [0]);
}
Class<t> Clazz is an explicit type. Direct use of the words will be an error:
Can not directly use <T>, then we need to get to <T> class<t> Clazz;
Here are two ways to get the generics <T> class<t> Clazz: One is to use a reflection class reflect
class<? Super t> Rawtype;
Rawtype = (Class <T>) ((Parameterizedtype) GetClass (). Getgenericsuperclass ()). Getactualtypearguments () [0];
The ' 0 ' in getactualtypearguments () [0] represents the first generic type. The second type uses Gson to obtain
class<? Super t> Rawtype;
Public Basecallback () {
This.mtype = Getsuperclasstypeparameter (GetClass ());
This.rawtype = (class< super t>) $Gson $types.getrawtype (mtype);
}
Static type Getsuperclasstypeparameter (Class<?> subclass) {
Type superclass = Subclass.getgenericsuperclass ();
if (superclass instanceof Class) {
throw new RuntimeException ("Missing type parameter.");
}
Parameterizedtype parameterized = (parameterizedtype) superclass;
Return $Gson $types.canonicalize (parameterized.getactualtypearguments () [0]);
}
class<? Super T> Rawtype is our data type for generics <T> class<t> Clazz
The above is a little bit of my record, I hope to help you.
Reference: http://wiki.jikexueyuan.com/project/java-reflection/java-type.html;
http://www.cnblogs.com/whitewolf/p/4355541.html;
Reprint Please indicate the source:
http://blog.csdn.net/sinat_15877283/article/details/50971262
This is from: "Winledon's Blog"