[英]Attempt to invoke virtual method 'java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String)' on a null object reference
[英]Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference despite initializing the object
好的,上次我問這個問題時,被我刪除了3個人。 可能還不清楚,對不起我的錯。 所以我正在使用改造來使api命中。 api返回一個JSON,該JSON的字段數據可以為null。 因此,JSON可能是這樣的。
{
"title": "Product",
"description": "A product from Acme's catalog",
"type": "object"
"data":null
}
如果不為null,它將類似於
{
"title": "Product",
"description": "A product from Acme's catalog",
"type": "object"
"data":{"b":"xyz","a":123}
}
現在我有一個像這樣的對象的模型類
public class A {
@Expose
public String title;
@Expose
public String description;
@Expose
public String type;
@Expose
public Data data =new Data();
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
}
這就是數據的模型
public class Data {
public Data(){
this.a=0;
this.b="";
}
@Expose
public double a;
@Expose
public String b="";
public Double getA() {
return a;
}
public void setA(Double a) {
this.a = a;
}
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
}
Retrofit將JSON轉換為A類型的Java對象。現在,我對A類型的對象所做的下一件事是將其轉換為B類型的另一個對象。
為了進行轉換,我使用了一個實用程序類。 其說明如下
This utility converts one java object to another java object.
* does not support Inheritance
* Mainly useful for when you have two Class one for Restful call and another for ORM suite
* if you get one object from RESTFUL call and another object to be created to save in ORM then generally we
* create another object and manually put the value by setter and getter
* just keep the same field name in both class and use this utility function to assign value from one to another
* and then use another to save in db. So no more stupid getter setter use, it handles nested class and Collection field .
現在我面臨的問題是該類引發異常
Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
這是我得到的唯一錯誤,僅此而已。 stacktrace是干凈的,只是此錯誤。 基本上,對象轉換失敗。 之所以很有可能是因為數據字段為null,因為在此之前我沒有收到任何此類錯誤。
這是我的實用程序類(負責對象轉換的代碼)中代碼的一部分。 我傳遞了兩個對象類型,一個是源,另一個是目標。 在這種情況下,源是類型A的對象。但是第一行導致了我在問題中提到的異常。
// get the class of source object
Class sourceObjectType = sourceObject.getClass();
// get the class of destination object
Class destinationObjectType = destinationObject.getClass();
現在,我不確定如何處理此異常。 我嘗試創建一個構造函數,以使Data不為null,但這不起作用。 如果有人可以提出建議或幫助我,那將是很棒的。 謝謝 !!
您可以先使用以下簡單條件檢查一下destinationObjectType是否為null:
if(destinationObjectType){
// handle your condition here
}
或者您可以處理異常:
try{
// get the class of source object
Class sourceObjectType = sourceObject.getClass();
// get the class of destination object
Class destinationObjectType = destinationObject.getClass();
}
catch(NullPointerException e){
// Handle your exception here
}
問候!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.