从字节数组创建对象(使用构造函数)

Create object from byte array (with constructor)

在我的项目中有一个class,经常需要序列化为字节数组。 我目前在 class 中有一个构造函数,它获取数组、解析它并创建一个新对象。完成后,构造函数从该(新)对象读取所需的字段并在 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;
  }
  ...
}

这样的代码可以正常工作,但问题是:是否可以直接创建(使用该构造函数)MyClass 对象,而无需创建 "newClass" 实例并手动设置所有值?

你不应该像那样反序列化你的对象,而是像 specification 指示的那样实现 readObject

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;   
}

不,这不可能。

但是您可以引入静态工厂方法,而不是创建两个 MyClass 对象的构造函数 MyClass(byte[])

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);
    }
}