2016-12-03 52 views
1

如何制作listObject的副本?如何制作自定义对象副本? Java

类的

的ListObject

static class listObject { 
     ArrayList<String> diseases; 
     ArrayList<String> images; 

     static class guide { 
      ArrayList<String> guideTitle; 
      ArrayList<String> guideText; 
      ArrayList<String> guideImage; 
     } 
    } 

这里是我的复制功能:

public static Object copy(Object orig) { 
     Object obj = null; 
     try { 
      // Write the object out to a byte array 
      ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
      ObjectOutputStream out = new ObjectOutputStream(bos); 
      out.writeObject(orig); 
      out.flush(); 
      out.close(); 

      // Make an input stream from the byte array and read 
      // a copy of the object back in. 
      ObjectInputStream in = new ObjectInputStream(
        new ByteArrayInputStream(bos.toByteArray())); 
      obj = in.readObject(); 
     } 
     catch(IOException e) { 
      e.printStackTrace(); 
     } 
     catch(ClassNotFoundException cnfe) { 
      cnfe.printStackTrace(); 
     } 
     return obj; 
    } 

当我调用拷贝()函数它返回NULL:

listObject list; 
listObject _tempList = new listObject(); 
list = (listObject) copy((Object) _tempList); 
+2

唯一可以通过'in.readObject'将'obj'设置为非空值的方式,所以它看起来像该方法返回null。 –

+2

您的listObject类是否实现'serializable'或'externalizable'接口?只有那些类可以从流中读取。 –

+0

上面是什么'salud'? – nullpointer

回答

0

listObject应该实现Serializable。如下所示更改listObject。

class listObject implements Serializable{ 
ArrayList<String> diseases; 
ArrayList<String> images; 

static class guide { 
    ArrayList<String> guideTitle; 
    ArrayList<String> guideText; 
    ArrayList<String> guideImage; 
} 
}