The deserialized object is null in all fields

I wrote my class Container<T>, which backs up its elements Tin several collections - the main one - List<T>, the others - different maps with data obtained from the elements, mainly for optimized searches.

The class is as follows:

class Container<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    private final List<T> items = Lists.newArrayList();
    private final Map<...> map1 = Maps.newHashMap();
    private final Map<...> map2 = Maps.newHashMap();
}

Standard serialization works like a charm, but cards do not need to be serialized. I tried to install cards as transientand use readObject()as follows:

class Container<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    private final List<T> items = Lists.newArrayList();
    private transient Map<...> map1;
    private transient Map<...> map2;

    public Container() {
        initContainer();
    }

    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        in.defaultReadObject();
        initContainer();
    }

    private void initContainer() {
        map1 = Maps.newHashMap();
        map2 = Maps.newHashMap();
        // prepare data in maps
        for (T item: items) {
            map1.put(...);
            map2.put(...);
        }
    }
}

A simple test with ObjectOutputStream.writeObject()and ObjectInputStream.readObject()works again. But when I integrate Containerinto a real application where this class is serialized and deserialized as part of other complex classes (actually on the Wicket page), strange things happen.

, :

  • Container (n) OK
  • Container
  • T (n-1) ( readObject())
  • in containerInit() List<T> (n) , (, ) - null - NPE

:

  • ( , readObject() )?
  • , , , ObjectInputStream , . - ?
  • - // , ?

.

+3
1

, Container.readObject(). . Container, .

:

parent children. , . readObject() , , . .

, .

0

Source: https://habr.com/ru/post/1755732/


All Articles