2016-03-18 63 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; 
} 
相关问题