【问题标题】:Create object from byte array (with constructor)从字节数组创建对象(使用构造函数)
【发布时间】: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


【解决方案1】:

不,这是不可能的。

但是,您可以引入静态工厂方法,而不是创建两个 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);
    }
}

【讨论】:

    【解决方案2】:

    您不应该像那样反序列化您的对象,而应按照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;   
    }
    

    【讨论】:

      猜你喜欢
      • 2013-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-20
      • 2012-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多