【发布时间】:2016-07-05 05:09:33
【问题描述】:
在我的项目中,我有一个经常需要序列化为字节数组的类。 我目前在我的类中有一个构造函数,它接受数组,解析它并创建一个新对象。完成后,构造函数从该(新)对象中读取所需字段并在类中设置适当的值。
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。
标签: java arrays object constructor bytearray