好了,上次我問過這個問題,它是由3人我之前downvoted刪除它。可能是不清楚,對不起我的錯。所以我正在使用改造來製作api命中。 api返回一個JSON,其中的字段數據可以爲null。所以JSON可以是這樣的。嘗試在空對象引用調用虛擬方法的java.lang.Class java.lang.Object.getClass()「儘管初始化對象
{
"title": "Product",
"description": "A product from Acme's catalog",
"type": "object"
"data":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 will conv ERT的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
這是我得到的唯一錯誤,沒有別的。堆棧跟蹤是乾淨的,只是這個錯誤。基本上對象轉換失敗。共振很可能是因爲數據字段爲空,因爲在此之前我沒有收到任何此類錯誤。
這是從我的工具類的一個代碼部分(所述一個負責對象轉換)。我將兩個對象類型傳遞給一個源和另一個目標。這種情況下的源代碼是A類型的對象。但第一行導致我在問題中提到的異常。
// get the class of source object
Class sourceObjectType = sourceObject.getClass();
// get the class of destination object
Class destinationObjectType = destinationObject.getClass();
現在我不知道如何處理這個異常。我試圖創建一個構造函數,以便Data不爲null,但這不起作用。如果有人能夠提出建議或幫助我,這將會很棒。謝謝 !!
顯然'null.getClass()'會拋出一個NPE ... – Selvin
但我的課不爲空,將現場數據,我甚至試圖對其進行初始化。 – varunkr
可能重複[什麼是空指針異常,以及如何解決它?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do -i-fix-it) – Selvin