In my project I have a class which often needs to be serialized to byte array. I currently have a constructor in my class which takes the array, parses it and creates a new object. Once it is done, the constructor reads needed fields from that (new) object and sets appropriate values in the class.
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;
}
...
}
Code like this works correctly, but the question is: Is it possible to create (with that constructor) MyClass object directly, without creating that "newClass" instance and setting all values manually?
newClass.