[英]NullPointerException creating generic type instance
這是我的課
public class ManagerForm<M extends Stuff>{
private Class<M>clazz;
private M manager;
public void setWorker(M manager){
this.manager=manager;
}
public M getWorker(){
return this.manager;
}
private final Class<M> getGenericClass() {
Class<M> persistentClass = null;
Type genericType = getClass().getGenericSuperclass();
if (genericType instanceof ParameterizedType) {
ParameterizedType pType = ((ParameterizedType) genericType);
// obtaining first generic type class
persistentClass = (Class<M>) pType.getActualTypeArguments()[0];
}
return persistentClass;
}
public ManagerForm(){
this.clazz=getGenericClass();
this.manager=this.clazz.newInstance();
}
}
在默認構造函數中,此行為this.user=this.clazz.newInstance();
我有NullPointer異常Request processing failed; nested exception is java.lang.NullPointerException
Request processing failed; nested exception is java.lang.NullPointerException
誰能幫我。 到底是怎么回事? 為什么clazz創建空實例? 我的錯誤在哪里?
提前致謝。
UPD
genericType屬於Object類型,並且不是ParameterizedType的實例。 這就是為什么函數getGenericType返回null的原因。 為什么?
當我使用Type genericType = getClass()
而不是Type genericType = getClass().getGenericSuperclass();
我可以得到ManagerForm類型。 但是ManagerForm也不屬於ParameterizedType實例嗎?
有人可以清除情況嗎?
在您的getGenericClass函數中:
genericType instanceof ParameterizedType
可能返回false,因此persistantClass為null。
我會說getGenericClass中的if塊沒有被執行。 因此,將返回persistentClass的初始值。 沒有運行代碼,我可能是錯誤的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.