0
下面我粘貼了我想運行的示例。Java ClassCastException從泛型實例中取參數化類型E「new ClazzXXX <E>()」
我可以很容易地獲得一個StringHome
實例的泛型,該實例擴展了Home<String>
,但我無法對new Home<String>()
實例做同樣的處理。 我如何獲得它?
我的目標是使mainKO
方法作爲mainOK
。
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public class Home<E> {
@SuppressWarnings ("unchecked")
public Class<E> getTypeParameterClass(){
Type type = getClass().getGenericSuperclass();
ParameterizedType paramType = (ParameterizedType) type;
return (Class<E>) paramType.getActualTypeArguments()[0];
}
private static class StringHome extends Home<String>{}
private static class StringBuilderHome extends Home<StringBuilder>{}
private static class StringBufferHome extends Home<StringBuffer>{}
public static void main(String[] args) throws Exception {
// this works fine
mainOK();
Thread.sleep(1000);
// this throws an error
mainKO();
}
/**
* This prints "String", "StringBuilder" and "StringBuffer"
*/
public static void mainOK() throws Exception {
Object object0 = new StringHome().getTypeParameterClass().newInstance();
Object object1 = new StringBuilderHome().getTypeParameterClass().newInstance();
Object object2 = new StringBufferHome().getTypeParameterClass().newInstance();
System.out.println(object0.getClass().getSimpleName());
System.out.println(object1.getClass().getSimpleName());
System.out.println(object2.getClass().getSimpleName());
}
/**
* This throws error:
* Exception in thread "main" java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
*/
public static void mainKO() throws Exception {
Object object0 = new Home<String>().getTypeParameterClass().newInstance();
Object object1 = new Home<StringBuilder>().getTypeParameterClass().newInstance();
Object object2 = new Home<StringBuffer>().getTypeParameterClass().newInstance();
System.out.println(object0.getClass().getSimpleName());
System.out.println(object1.getClass().getSimpleName());
System.out.println(object2.getClass().getSimpleName());
}
}
這個類印刷品的執行了這一點:
String
StringBuilder
StringBuffer
Exception in thread "main" java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
at org.command4j.core.commands.utils.Home.getTypeParameterClass(Home.java:13)
at org.command4j.core.commands.utils.Home.mainKO(Home.java:46)
at org.command4j.core.commands.utils.Home.main(Home.java:26)
你只是不能。 –
你能解釋爲什麼這在技術上不可行嗎? – madx