在我的項目中,我有一個類經常需要序列化爲字節數組。 我目前在我的類中有一個構造函數,它接受數組,解析它並創建一個新對象。一旦完成,構造函數將從該(新)對象讀取所需的字段並在該類中設置適當的值。從字節數組創建對象(帶構造函數)
public class MyClass implements Serializable {
private int fieldOne;
private boolean fieldTwo;
...
// This is default constructor
public MyClass(){
}
// This is the constructor we are interested in
public MyClass(byte[] input){
MyClass newClass = null;
try(ByteArrayInputStream bis = new ByteArrayInputStream(input);
ObjectInput in = new ObjectInputStream(bis)) {
newClass = (MyClass) in.readObject();
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
if (newClass != null) {
this.fieldOne = newClass.getFieldOne;
this.fieldTwo = newClass.getFieldTwo;
...
}
}
public int getFieldOne(){
return fieldOne;
}
public boolean getFieldTwo(){
return fieldTwo;
}
...
}
這樣的代碼工作正常,但問題是:是否有可能創造(與構造函數)MYCLASS直接對象,而不產生「的NewClass」實例和手動設置的所有值?
爲什麼你需要它是一個構造?你可以使它成爲一個靜態方法,並簡單地返回'newClass'。 –