2016-03-18 60 views
0

在我的項目中,我有一個類經常需要序列化爲字節數組。 我目前在我的類中有一個構造函數,它接受數組,解析它並創建一個新對象。一旦完成,構造函數將從該(新)對象讀取所需的字段並在該類中設置適當的值。從字節數組創建對象(帶構造函數)

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」實例和手動設置的所有值?

+0

爲什麼你需要它是一個構造?你可以使它成爲一個靜態方法,並簡單地返回'newClass'。 –

回答

1

不,這是不可能的。

但不是一個構造MyClass(byte[]),然後創建兩個MyClass對象,你可以引入一個靜態工廠方法:

public static MyClass create(byte[] input) { 
    try(ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(input))) { 
     return (MyClass)in.readObject(); 
    } 
    catch (Exception e) { 
     throw new IllegalStateException("could not create object", e); 
    } 
} 
1

你不應該反序列化你的對象是一樣的,而實現readObjectspecification表示:

private void readObject(ObjectInputStream in) 
    throws IOException, ClassNotFoundException { 

    in.defaultReadObject(); 

    // custom 
    this.fieldOne = in.readXXX(); 
    this.fieldTwo = in.readXXX(); 
} 

而且這是專門針對自定義序列化,你爲什麼不直接使用API​​,或進行靜態方法檢索對象:

public static MyClass readFromByteArray(byte[] input) { 
    Myclass obj = null; 

    try (ByteArrayInputStream bis = new ByteArrayInputStream(input); 
     ObjectInputStream ois = new ObjectInputStream(bis)) { 
     obj = (MyClass) in.readObject(); 
    } catch (ClassNotFoundException | IOException e) { 
     e.printStackTrace(); 
    } 

    return obj; 
} 
相關問題