在我的项目中,我有一个类经常需要序列化为字节数组。 我目前在我的类中有一个构造函数,它接受数组,解析它并创建一个新对象。一旦完成,构造函数将从该(新)对象读取所需的字段并在该类中设置适当的值。从字节数组创建对象(带构造函数)
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'。 –