2014-01-14 4 views
0

개체에 대한 참조를 유지할 수 있지만이 참조를 통해 일련 화되기를 원하지는 않습니다. Java에서 직렬화 된 객체에 대한 참조를 유지하는 방법은 무엇입니까?

는 더 명확 내가 NodesNode의 목록이 포함 된 NetworkConnections의 목록을 포함했습니다의 Connection 다른 Nodes에 대한 참조를 포함 확인하십시오. 내가이 StackOverflowError에 결과 큰 Network의 직렬화 종류를하려고 할 때

문제는 내가 그이 원인이 있으리라 믿고있어 상황은 다음과 같다입니다 :

  • 직렬화가 Network 시작하여 직렬화하려고
      Node
    • 그런 다음 그것은 다른 노드 등등 다음 Node 및 직렬화하려고
    • 에 대한 참조를 포함하는 제 직렬화 연결을 시도하고, 직렬화 재귀 통해 서 진행 H Connection의 참조가 transient으로 표시하는 경우가 직렬화에는 문제가 없지만, 다음 = 직렬화 여기

    null 문제

    를 재생하는 샘플은 참조되는 오버플
  • 를 일으키는 모든 노드

    Network.java

    import java.io.Serializable; 
    import java.util.ArrayList; 
    
    public class Network implements Serializable { 
        private static final long serialVersionUID = 1399116563470735156L; 
    
        ArrayList<Layer>layers; 
    
        public Network() { 
         layers= new ArrayList<Layer>(); 
        } 
    
        //connect each layer to next layer 
        public void connectAllLayers(){ 
         for (int i = 0; i < layers.size()-1; i++) { 
          layers.get(i).connectTo(layers.get(i+1)); 
         } 
        } 
    } 
    

    층. 자바

    import java.io.Serializable; 
    import java.util.ArrayList; 
    
    
    public class Layer implements Serializable{ 
        private static final long serialVersionUID = -5519150448729707106L; 
    
        public ArrayList<Node>nodes; 
    
        public Layer(int nodeCount) { 
         nodes = new ArrayList<Node>(); 
         for (int i = 0; i < nodeCount; i++) { 
          nodes.add(new Node()); 
         } 
        } 
    
        //connect all nodes in a layer to all nodes in the other layer 
        public void connectTo(Layer layer){ 
         for (Node myNode : nodes) { 
          for (Node toNode : nodes) { 
           myNode.connectTo(toNode); 
          } 
         } 
        } 
    } 
    

    Node.java

    import java.io.Serializable; 
    import java.util.ArrayList; 
    
    
    public class Node implements Serializable{ 
        private static final long serialVersionUID = 6323513316304801012L; 
    
        public ArrayList<Connection>connections; 
        public double x,y,z,a,b,c;//some variables to simulate memory usage 
    
        public Node() { 
         connections = new ArrayList<Connection>(); 
         x=15; 
        } 
    
        public void connectTo(Node node){ 
         Connection connection = new Connection(this, node); 
         this.connections.add(connection); 
         node.connections.add(connection); 
        } 
    } 
    

    Connection.java

    import java.io.Serializable; 
    
    public class Connection implements Serializable { 
        private static final long serialVersionUID = 7578299749680304407L; 
    
        public Node from; 
        public Node to; 
        public double weight; 
    
        public Connection(Node from, Node to) { 
         this.from = from; 
         this.to = to; 
        } 
    } 
    

    Main.java

    01,239,007,781,355,

    질문을 더 일반적으로 만들려면 오버플로가 발생하지 않고 모든 노드에 대한 참조가 들어있는 목록이 있다고 가정하고 연결된 노드 클래스와 같은 그래프를 직렬화 할 수 있습니까?

  • 답변

    0

    Java는 이미 직렬화 된 객체에 대한 참조 만 저장하여 그래프를 잘 serialize합니다. 그러나 깊이 우선 방식으로 재귀를 사용하며 그래프가 매우 깊습니다 (스택 오버플로가 발생하기 전에 548 개의 노드가 있습니다).

    깊이별로 레이어를 정렬하고 내림차순으로 직렬화합니다. 이렇게하면 직렬화 중에 심한 재귀를 방지 할 수 있습니다.

    +0

    내 네트워크가 너무 큰 것을 완전히 알고 있어요, 원래 버전은 신경망입니다 그런 식으로해야합니다. 거기에 BFS 스타일로 그것을 할 수있는 방법이 있습니까? 또는 연결 개체를 통해 DFS를 방지하지만 참조 만 유지? –

    +0

    "가장 먼저 가장 먼저"정렬 된 객체 목록 ('List ')을 어떻게 든 작성할 수 있다면, 그 목록을 먼저 직렬화하고 네트워크 바로 다음에 (동일한 스트림에서) 직렬화 할 수 있습니다. 네트워크 객체가 직렬화되면, 전체 직렬화가 아닌 모든 계층 엔트리가 참조가됩니다. 그런 다음 목록 및 네트워크 개체를 deserialize하고 목록을 무시할 수 있습니다. –

    +0

    나는 당신 생각을 가지고 있다고 생각하지만,이 경우에는'List '을 가질 필요가 없다. 모두 내가 할 필요가 앞으로 레이어 대신 레이어를 serialize하는 것입니다, 또 다른 일이있다, 여기에 모든 가장자리는 양방향입니다, 만약 그 방법을 지키면 가장 깊은 노드가 될거야,하지만 난 그것을 직렬화 중에 하나의 방향으로 만들 수있을 것 같아요 , 내가 비 직렬화 할 때, 나는 그들을 다시 재구성 할 것이고, 나는 이것을 지금 시도 할 것이다. –

    0

    이 코드를 사용하면 도움이 될 것입니다. 프로덕션에 사용하는 경우 신중하게 테스트해야합니다. 한 가지, 그것은 클래스에 대한 사용자 지정 직렬화 루틴을 찾지 않습니다.하지만 그게 목적에 맞는 것 같아요.

    이 두 클래스의 SequentialObjectOutputStream 및 SequentialObjectInputStream

    import java.io.*; 
    import java.util.*; 
    import java.lang.reflect.*; 
    import android.util.*; 
    
    public class SequentialObjectOutputStream extends DataOutputStream 
    implements ObjectOutput 
    { 
        interface FieldGetAction 
        { 
         void get(Object obj, Field field) throws IllegalAccessException, IOException; 
        } 
    
        interface ArrayGetAction 
        { 
         void get(Object array, int Index) throws ArrayIndexOutOfBoundsException, IOException;  
        } 
    
        public HashMap<Class, FieldGetAction> Primatives; 
        public HashMap<Class, ArrayGetAction> ArrayPrimatives; 
    
        public SequentialObjectOutputStream(OutputStream stream) 
        { 
         super(stream); 
    
         Primatives = new HashMap<Class, FieldGetAction>(); 
    
         try 
         { 
          Primatives.put(boolean.class, 
          new FieldGetAction() 
          { 
           public void get(Object obj, Field field) throws IllegalAccessException, IOException 
           { 
            boolean x = field.getBoolean(obj); 
            writeBoolean(x); 
    
           } 
          }); 
    
          Primatives.put(byte.class, 
           new FieldGetAction() 
           { 
            public void get(Object obj, Field field) throws IllegalAccessException, IOException 
            { 
             byte x = field.getByte(obj); 
             writeByte(x); 
    
            } 
           }); 
    
    
          Primatives.put(short.class, 
           new FieldGetAction() 
           { 
            public void get(Object obj, Field field) throws IllegalAccessException, IOException 
            { 
             short x = field.getShort(obj); 
             writeShort(x); 
    
            } 
           }); 
    
    
          Primatives.put(int.class, 
           new FieldGetAction() 
           { 
            public void get(Object obj, Field field) throws IllegalAccessException, IOException 
            { 
             int x = field.getInt(obj); 
             writeInt(x); 
    
            } 
           }); 
    
    
          Primatives.put(long.class, 
           new FieldGetAction() 
           { 
            public void get(Object obj, Field field) throws IllegalAccessException, IOException 
            { 
             long x = field.getLong(obj); 
             writeLong(x); 
    
            } 
           }); 
    
    
          Primatives.put(char.class, 
           new FieldGetAction() 
           { 
            public void get(Object obj, Field field) throws IllegalAccessException, IOException 
            { 
             char x = field.getChar(obj); 
             writeChar(x); 
    
            } 
           }); 
    
    
          Primatives.put(float.class, 
           new FieldGetAction() 
           { 
            public void get(Object obj, Field field) throws IllegalAccessException, IOException 
            { 
             float x = field.getFloat(obj); 
             writeFloat(x); 
    
            } 
           }); 
    
    
          Primatives.put(double.class, 
           new FieldGetAction() 
           { 
            public void get(Object obj, Field field) throws IllegalAccessException, IOException 
            { 
             double x = field.getDouble(obj); 
             writeDouble(x); 
            } 
           }); 
    
    
          Primatives.put(String.class, 
           new FieldGetAction() 
           { 
            public void get(Object obj, Field field) throws IllegalAccessException, IOException 
            { 
             String x = (String) field.get(obj); 
             writeUTF(x); 
    
            } 
           }); 
         } catch(Exception e) 
         { 
          Log.e("SOb", Log.getStackTraceString(e)); 
         } 
    
    
    
         ArrayPrimatives = new HashMap<Class, ArrayGetAction>(); 
    
         try 
         { 
          ArrayPrimatives.put(boolean.class, 
           new ArrayGetAction() 
           { 
            public void get(Object obj, int index) throws ArrayIndexOutOfBoundsException, IOException 
            { 
             boolean x = Array.getBoolean(obj, index); 
             writeBoolean(x); 
    
            } 
           }); 
    
          ArrayPrimatives.put(byte.class, 
           new ArrayGetAction() 
           { 
            public void get(Object obj, int index) throws ArrayIndexOutOfBoundsException, IOException 
            { 
             byte x = Array.getByte(obj, index); 
             writeByte(x); 
    
            } 
           }); 
    
    
          ArrayPrimatives.put(short.class, 
           new ArrayGetAction() 
           { 
            public void get(Object obj, int index) throws ArrayIndexOutOfBoundsException, IOException 
            { 
             short x = Array.getShort(obj, index); 
             writeShort(x); 
    
            } 
           }); 
    
    
          ArrayPrimatives.put(int.class, 
           new ArrayGetAction() 
           { 
            public void get(Object obj, int index) throws ArrayIndexOutOfBoundsException, IOException 
            { 
             int x = Array.getInt(obj, index); 
             writeInt(x); 
    
            } 
           }); 
    
    
          ArrayPrimatives.put(long.class, 
           new ArrayGetAction() 
           { 
            public void get(Object obj, int index) throws ArrayIndexOutOfBoundsException, IOException 
            { 
             long x = Array.getLong(obj, index); 
             writeLong(x); 
    
            } 
           }); 
    
    
          ArrayPrimatives.put(char.class, 
           new ArrayGetAction() 
           { 
            public void get(Object obj, int index) throws ArrayIndexOutOfBoundsException, IOException 
            { 
             char x = Array.getChar(obj, index); 
             writeChar(x); 
    
            } 
           }); 
    
    
          ArrayPrimatives.put(float.class, 
           new ArrayGetAction() 
           { 
            public void get(Object obj, int index) throws ArrayIndexOutOfBoundsException, IOException 
            { 
             float x = Array.getFloat(obj, index); 
             writeFloat(x); 
    
            } 
           }); 
    
    
          ArrayPrimatives.put(double.class, 
           new ArrayGetAction() 
           { 
            public void get(Object obj, int index) throws ArrayIndexOutOfBoundsException, IOException 
            { 
             double x = Array.getDouble(obj, index); 
             writeDouble(x); 
            } 
           }); 
    
    
          ArrayPrimatives.put(String.class, 
           new ArrayGetAction() 
           { 
            public void get(Object obj, int index) throws ArrayIndexOutOfBoundsException, IOException 
            { 
             String x = (String) Array.get(obj, index); 
             writeUTF(x); 
    
            } 
           }); 
         } catch(Exception e) 
         { 
          Log.e("SOb", Log.getStackTraceString(e)); 
         } 
    
        } 
    
        class State 
        { 
         public ArrayList<Object> OStack = new ArrayList<Object>(); 
    
         public long currentId = 1; 
    
         public HashMap<Object, Long> References = new HashMap<Object, Long>(); 
    
        } 
    
        public void writeObject(Object A) throws IOException, NotSerializableException 
        { 
         final State state = new State(); 
    
         state.OStack.add(0, A); 
    
         LinkedList<Object> ForStack = new LinkedList<Object>(); 
    
         while (!(state.OStack.size() == 0)) 
         { 
          Object Current = state.OStack.get(0); 
          state.OStack.remove(0); 
    
          if (((Serializable) Current) == null) 
          { 
           throw new NotSerializableException(); 
          } 
    
    
          //Type C = Current.getClass(); 
    
          Class C = Current.getClass(); 
    
          Log.i("SOb", "placing #"+Long.toString(state.currentId)+" of "+C.getCanonicalName()+" on graph"); 
          state.References.put(Current, state.currentId); 
          state.currentId++; 
    
          ForStack.add(Current); 
    
          if (C.isArray()) 
          { 
           //Array array = (Array) Current; 
           Class Ctype = C.getComponentType(); 
    
           if (ArrayPrimatives.keySet().contains(Ctype) == false) 
           { 
            for (int I=0; I<Array.getLength(Current); I++) 
            { 
             Object o = Array.get(Current, I); 
    
             if ((o != null) && (state.References.keySet().contains(o) == false)) 
             { 
              if (state.OStack.contains(o) == false) state.OStack.add(state.OStack.size(), o); 
             } 
    
            } 
           } 
          } else 
          { 
           for (Class Cur = C; Cur != null; Cur = Cur.getSuperclass()) 
           { 
    
            Field[] fields = Cur.getDeclaredFields(); 
    
            for (Field f : fields) 
            { 
             if (Modifier.isStatic(f.getModifiers())) 
             { 
              continue; 
             } 
    
             f.setAccessible(true); 
    
             if (f.isAccessible() == false) 
             { 
             // Log.i("SOb", "  isAccessible = false"); 
              continue; 
             } 
    
             Class type = f.getType(); 
             //Log.i("SOb", "  field \""+f.getName()+"\" of "+type.getCanonicalName()); 
    
             if (Primatives.keySet().contains(type) == false) 
             {  
              try 
              { 
               Object o = f.get(Current); 
    
               if ((o != null) && (state.References.keySet().contains(o) == false)) 
               { 
                if (state.OStack.contains(o) == false) state.OStack.add(state.OStack.size(), o); 
               } 
    
              } catch (IllegalAccessException e) 
              { 
               Log.e("SOb", Log.getStackTraceString(e)); 
              } 
             } 
            } 
           } 
          } 
         } 
    
         writeLong(state.References.size()); 
    
         for (Object O : ForStack) 
         { 
          Serializable s = (Serializable) O; 
    
         // if (s != null) 
          { 
           Class cl = O.getClass(); 
    
           String name = cl.getName(); 
    
           writeUTF(name); 
    
           if (cl.isArray()) 
           { 
            Class components = cl.getComponentType(); 
    
            ArrayGetAction action; 
    
            //Array array = (Array) O; 
    
            if (ArrayPrimatives.keySet().contains(components)) 
            { 
             action = ArrayPrimatives.get(components); 
            } else 
            { 
             action = new ArrayGetAction() 
             { 
              public void get(Object array, int index) throws ArrayIndexOutOfBoundsException, IOException  
              { 
               Object O = Array.get(array, index); 
               if (O==null) writeLong(0); 
               else writeLong(state.References.get(O)); 
              } 
             }; 
            } 
    
            int length = Array.getLength(O); 
    
            writeInt(length); 
    
            for (int I=0; I<length; I++) 
            { 
             action.get(O, I); 
            } 
    
           } else 
           { 
            for (Class Cur = cl; Cur != null; Cur = Cur.getSuperclass()) 
            { 
             Field[] fields = Cur.getDeclaredFields(); 
    
             for (Field F : fields) 
             { 
              Class FieldType = F.getType(); 
    
              F.setAccessible(true); 
    
              if (F.isAccessible() && (Modifier.isStatic(FieldType.getModifiers()))) 
              { 
               FieldGetAction action; 
    
               //Array array = (Array) O; 
    
               if (Primatives.keySet().contains(FieldType)) 
               { 
                action = Primatives.get(FieldType); 
               } else 
               { 
                action = new FieldGetAction() 
                { 
                 public void get(Object obj, Field index) throws IllegalAccessException, IOException  
                 { 
                  Object O = index.get(obj); 
                  if (O==null) writeLong(0); 
                  else writeLong(state.References.get(O)); 
                 } 
                }; 
               } 
    
               try 
               { 
                action.get(O, F); 
               } catch (IllegalAccessException e) 
               { 
                Log.e("SOb", Log.getStackTraceString(e)); 
               } 
    
              } 
             } 
    
            } 
           } 
          } 
         } 
        } 
    } 
    

    SequentialObjectInputStream 구성

    import java.io.*; 
    import java.util.*; 
    import java.lang.reflect.*; 
    
    import android.util.*; 
    
    public class SequentialObjectInputStream extends DataInputStream implements ObjectInput 
    { 
        interface FieldPutAction 
        { 
         void put(Object obj, Field field) throws IllegalAccessException, IOException; 
        } 
    
        interface ArrayPutAction 
        { 
         void put(Object obj, int index) throws ArrayIndexOutOfBoundsException, IOException; 
        } 
    
        public HashMap<Class, FieldPutAction> Primatives; 
        public HashMap<Class, ArrayPutAction> ArrayPrimatives; 
    
        public SequentialObjectInputStream(InputStream stream) 
        { 
         super(stream); 
    
         Primatives = new HashMap<Class, FieldPutAction>(); 
    
         try 
         { 
          Primatives.put(boolean.class, 
           new FieldPutAction() 
           { 
            public void put(Object obj, Field field) throws IllegalAccessException, IOException 
            { 
             boolean x = readBoolean(); 
             field.setBoolean(obj, x); 
    
            } 
           }); 
    
          Primatives.put(byte.class, 
           new FieldPutAction() 
           { 
            public void put(Object obj, Field field) throws IllegalAccessException, IOException 
            { 
             byte x = readByte(); 
             field.setByte(obj, x); 
    
            } 
           }); 
    
    
          Primatives.put(short.class, 
           new FieldPutAction() 
           { 
            public void put(Object obj, Field field) throws IllegalAccessException, IOException 
            { 
             short x = readShort(); 
             field.setShort(obj, x); 
    
            } 
           }); 
    
    
          Primatives.put(int.class, 
           new FieldPutAction() 
           { 
            public void put(Object obj, Field field) throws IllegalAccessException, IOException 
            { 
             int x = readInt(); 
             field.setInt(obj, x); 
    
            } 
           }); 
    
    
          Primatives.put(long.class, 
           new FieldPutAction() 
           { 
            public void put(Object obj, Field field) throws IllegalAccessException, IOException 
            { 
             long x = readLong(); 
             field.setLong(obj, x); 
    
            } 
           }); 
    
    
          Primatives.put(char.class, 
           new FieldPutAction() 
           { 
            public void put(Object obj, Field field) throws IllegalAccessException, IOException 
            { 
             char x = readChar(); 
             field.setChar(obj, x); 
    
            } 
           }); 
    
    
          Primatives.put(float.class, 
           new FieldPutAction() 
           { 
            public void put(Object obj, Field field) throws IllegalAccessException, IOException 
            { 
             float x = readFloat(); 
             field.setFloat(obj, x); 
    
            } 
           }); 
    
    
          Primatives.put(double.class, 
           new FieldPutAction() 
           { 
            public void put(Object obj, Field field) throws IllegalAccessException, IOException 
            { 
             double x = readDouble(); 
             field.setDouble(obj, x); 
    
            } 
           }); 
    
    
          Primatives.put(String.class, 
           new FieldPutAction() 
           { 
            public void put(Object obj, Field field) throws IllegalAccessException, IOException 
            { 
             String x = readUTF(); 
             field.set(obj, x); 
    
            } 
           }); 
         } catch(Exception e) 
         { 
          Log.e("SOb", Log.getStackTraceString(e)); 
         } 
    
         ArrayPrimatives = new HashMap<Class, ArrayPutAction>(); 
    
         try 
         { 
          ArrayPrimatives.put(boolean.class, 
           new ArrayPutAction() 
           { 
            public void put(Object obj, int index) throws ArrayIndexOutOfBoundsException, IOException 
            { 
             boolean x = readBoolean(); 
             Array.setBoolean(obj, index, x); 
            } 
           }); 
    
          ArrayPrimatives.put(byte.class, 
           new ArrayPutAction() 
           { 
            public void put(Object obj, int index) throws ArrayIndexOutOfBoundsException, IOException 
            { 
             byte x = readByte(); 
             Array.setByte(obj, index, x); 
    
            } 
           }); 
    
    
          ArrayPrimatives.put(short.class, 
           new ArrayPutAction() 
           { 
            public void put(Object obj, int index) throws ArrayIndexOutOfBoundsException, IOException 
            { 
             short x = readShort(); 
             Array.setShort(obj, index, x); 
    
            } 
           }); 
    
    
          ArrayPrimatives.put(int.class, 
           new ArrayPutAction() 
           { 
            public void put(Object obj, int index) throws ArrayIndexOutOfBoundsException, IOException 
            { 
             int x = readInt(); 
             Array.setInt(obj, index, x); 
    
            } 
           }); 
    
    
          ArrayPrimatives.put(long.class, 
           new ArrayPutAction() 
           { 
            public void put(Object obj, int index) throws ArrayIndexOutOfBoundsException, IOException 
            { 
             long x = readLong(); 
             Array.setLong(obj, index, x); 
    
            } 
           }); 
    
    
          ArrayPrimatives.put(char.class, 
           new ArrayPutAction() 
           { 
            public void put(Object obj, int index) throws ArrayIndexOutOfBoundsException, IOException 
            { 
             char x = readChar(); 
             Array.setChar(obj, index, x); 
    
            } 
           }); 
    
    
          ArrayPrimatives.put(float.class, 
           new ArrayPutAction() 
           { 
            public void put(Object obj, int index) throws ArrayIndexOutOfBoundsException, IOException 
            { 
             float x = readFloat(); 
             Array.setFloat(obj, index, x); 
    
            } 
           }); 
    
    
          ArrayPrimatives.put(double.class, 
           new ArrayPutAction() 
           { 
            public void put(Object obj, int index) throws ArrayIndexOutOfBoundsException, IOException 
            { 
             double x = readDouble(); 
             Array.setDouble(obj, index, x); 
    
            } 
           }); 
    
    
          ArrayPrimatives.put(String.class, 
           new ArrayPutAction() 
           { 
            public void put(Object obj, int index) throws ArrayIndexOutOfBoundsException, IOException 
            { 
             String x = readUTF(); 
             Array.set(obj, index, x); 
    
            } 
           }); 
         } catch(Exception e) 
         { 
          Log.e("SOb", Log.getStackTraceString(e)); 
         } 
        } 
    
    
        @Override 
        public Object readObject() throws ClassNotFoundException, IOException 
        { 
         long Total = readLong(); 
    
         Log.i("SOb", "readObject : " + Long.toString(Total) + " objects in graph"); 
    
         HashMap<Long, Object> References = new HashMap<Long, Object>(); 
    
         long currentId = 1; 
    
         HashMap<Object, HashMap<Field, Long>> refCache = 
          new HashMap<Object, HashMap<Field, Long>>(); 
         final HashMap<Object, HashMap<Integer, Long>> arefCache = 
          new HashMap<Object, HashMap<Integer,Long>>(); 
    
         for (int I=0; I < Total; I++) 
         { 
          String Name = readUTF(); 
          Class C = Class.forName(Name); 
    
          Log.i("SOb", "Object of "+C.getCanonicalName() +" on graph"); 
    
          int adim = 0; 
    
          Object O = null; 
    
          if (C.isArray()) 
          { 
           Class ComponentType = C.getComponentType(); 
    
           int Size = readInt(); 
    
           Log.i("SOb", "array of "+ComponentType.getCanonicalName() + ", " + Long.toString(Size) + " elements");   
           O = Array.newInstance(ComponentType, Size); 
    
           References.put(currentId, O); 
           currentId++; 
    
           ArrayPutAction action = null; 
    
           if (ArrayPrimatives.keySet().contains(ComponentType)) 
           { 
            action = ArrayPrimatives.get(ComponentType); 
           } else 
           { 
            arefCache.put(O, new HashMap<Integer, Long>()); 
    
            action = new ArrayPutAction() 
            { 
             public void put(Object O, int Index) throws ArrayIndexOutOfBoundsException , IOException 
             { 
              long Ref = readLong(); 
    
              arefCache.get(O).put(Index, Ref); 
             } 
            }; 
           } 
    
           for (int index=0; index< Size; index++) 
           { 
            action.put(O,index); 
           } 
    
          } else 
          { 
    
          try 
          { 
    
           O = 
            C.getConstructor(new Class[0]).newInstance(new Object[0]); 
          } catch(InstantiationException e) 
          { 
           Log.e("SOb", Log.getStackTraceString(e)); 
          } catch(NoSuchMethodException e) 
          { 
           Log.e("SOb", Log.getStackTraceString(e)); 
          } catch(IllegalAccessException e) 
          { 
           Log.e("SOb", Log.getStackTraceString(e)); 
          } catch(InvocationTargetException e) 
          { 
           Log.e("SOb", Log.getStackTraceString(e)); 
          } 
    
          References.put(currentId, O); 
          currentId++; 
          refCache.put(O, new HashMap<Field, Long>()); 
    
          for (Field F : C.getFields()) 
          { 
           if (F.isAccessible()) 
           { 
            Class T = F.getType(); 
    
            if (Primatives.containsKey(T)) 
            { 
             try 
             { 
              Primatives.get(T).put(O, F); 
             } catch (IllegalAccessException e) 
             { 
    
             } 
            } else 
            { 
             refCache.get(O).put(F, readLong()); 
            } 
           } 
          } 
    
         } 
         } 
         for (long I=0; I < Total; I++) 
         { 
    
          Object O = References.get(I+1); 
    
          Class C = O.getClass(); 
    
          //Log.i("SOb", "get reference "+Long.toString(I)+" "+C.getCanonicalName()); 
    
    
          if (C.isArray()) 
          { 
           HashMap<Integer,Long> aref_table = arefCache.get(O); 
    
           if (ArrayPrimatives.containsKey(C.getComponentType()) == false) 
           { 
    
            int len = Array.getLength(O); 
    
            for (int index=0; index<len; index++) 
            { 
             long r = aref_table.get(index); 
             Object ref = r == 0 ? null : References.get(r); 
    
             Array.set(O, index, ref); 
            } 
           } 
    
          } else 
          { 
    
          HashMap<Field, Long> ref_table = refCache.get(O); 
    
          for (Field F : C.getFields()) 
          { 
           if (F.isAccessible()) 
           { 
            Class T = F.getType(); 
    
            if (Primatives.containsKey(T) == false) 
            { 
             try 
             { 
              long r = ref_table.get(F); 
              Object ref = r == 0 ? null : References.get(r); 
    
              F.set(O, ref); 
             } catch (IllegalAccessException e) 
             { 
              Log.e("SOb", Log.getStackTraceString(e)); 
             } 
    
            } 
           } 
          } 
          } 
    
         } 
    
    
         return References.get((Long) (long) 1); 
        } 
    
    } 
    

    SequentialObjectOutputStream

    +0

    코드는 놀라운 나는 인정해야하지만 정확히 무엇을 얻을 수 없습니다. 내가 일반적으로 이해 한 것은 당신이 BFS 방식으로 객체를 가로 지르고, 당신이 HashMap에서 직렬화하는 각 객체에 대한 참조를 유지 한 다음 그것을 쓰는 것입니다. 일반적으로 방법이 어떻게 작동하는지 설명해 주시겠습니까? (아마도 일부 의견이나 일반적인 설명) –

    +0

    알리, 내 답변의 지연에 대한 사과. 간단히 말해, java에는 2 진 값, 필드 및 배열의 ​​저장을위한 두 가지 기본 모드가 있습니다. 이것은 둘 다 처리하는 방법을 제시합니다. 중요한 클래스의 이름을 스트림에 씁니다. 그런 다음 클래스에서 Field 객체 목록에 액세스합니다. Primatives와 ArrayPrimatives로 인 코드 된 접근자를 사용하여 둘 중 하나에 대한 IO를 처리하는 액션이 ​​호출됩니다. 개체를 넣고 가져 오는 IO 메서드는 목록을 활용하여 재귀를 피할 수 있으므로 참조가 설정되어 즉시 작성할 수 있습니다. 마지막으로 일어나는 픽스 업입니다. – RofaMagius

    관련 문제