2015-01-04 4 views
4

Я написал класс, который работает в сочетании с сериализацией объектов. На этапе сериализации, похоже, происходит исключение. Я не смог ничего найти об этом исключении. Я также не смог найти внутренний класс с псевдонимом Node в HashMap.

[04/01/15 2:33 PM]: java.io.NotSerializableException: java.util.HashMap$Node 
[04/01/15 2:33 PM]:  at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184) 
[04/01/15 2:33 PM]:  at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348) 
[04/01/15 2:33 PM]:  at java.util.ArrayList.writeObject(ArrayList.java:762) 
[04/01/15 2:33 PM]:  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
[04/01/15 2:33 PM]:  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
[04/01/15 2:33 PM]:  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
[04/01/15 2:33 PM]:  at java.lang.reflect.Method.invoke(Method.java:483) 
[04/01/15 2:33 PM]:  at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:988) 
[04/01/15 2:33 PM]:  at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496) 
[04/01/15 2:33 PM]:  at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432) 
[04/01/15 2:33 PM]:  at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178) 
[04/01/15 2:33 PM]:  at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548) 
[04/01/15 2:33 PM]:  at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509) 
[04/01/15 2:33 PM]:  at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432) 
[04/01/15 2:33 PM]:  at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178) 
[04/01/15 2:33 PM]:  at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348) 
[04/01/15 2:33 PM]:  at ab.server.data.ServerData.saveField(ServerData.java:157) 
[04/01/15 2:33 PM]:  at ab.server.data.ServerData.processQueue(ServerData.java:195) 
[04/01/15 2:33 PM]:  at ab.Server.lambda$0(Server.java:260) 
[04/01/15 2:33 PM]:  at ab.Server$$Lambda$15/2011997442.run(Unknown Source) 
[04/01/15 2:33 PM]:  at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) 
[04/01/15 2:33 PM]:  at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308) 
[04/01/15 2:33 PM]:  at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180) 
[04/01/15 2:33 PM]:  at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294) 
[04/01/15 2:33 PM]:  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) 
[04/01/15 2:33 PM]:  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) 
[04/01/15 2:33 PM]:  at java.lang.Thread.run(Thread.java:745) 

Это класс, который сериализуется.

public class WellOfGoodWill implements Serializable { 

    private static final long serialVersionUID = -3335621107999346623L; 

    /** 
    * The total number of winners possible for each draw 
    */ 
    private static final int MAXIMUM_WINNERS = 3; 

    /** 
    * Compares the value of an entry 
    */ 
    private static final Comparator<Entry<String, Integer>> HIGHEST_VALUE = Entry.comparingByValue(); 

    /** 
    * Contains all of the entries for the week 
    */ 
    private HashMap<String, Integer> entries = new HashMap<>(); 

    /** 
    * Winners of the previous week 
    */ 
    private Collection<Entry<String, Integer>> winners; 

    /** 
    * The date the week is over. The initial date is set. 
    */ 
    private Date date = Misc.getFutureDate(2014, Calendar.DECEMBER, 28, 18, 0, 0); 

    /** 
    * Requests that an update be made on the entries variable. 
    * @param player the key being updated 
    * @param amount the amount being added 
    */ 
    public void update(String player, Integer amount) { 
     if (!entries.containsKey(player)) { 
      entries.put(player, amount); 
     } else { 
      int oldValue = entries.get(player); 
      entries.replace(player, oldValue, oldValue + amount); 
     } 
     Server.getServerData().setWellOfGoodWill(this); 
    } 

    /** 
    * Clears all entries in the map 
    */ 
    public void clear() { 
     entries.clear(); 
    } 

    /** 
    * Determines the weekly winner based on their contributions 
    * @return the winner 
    */ 
    public Collection<Entry<String, Integer>> getSortedResults() { 
     List<Entry<String, Integer>> list = new ArrayList<>(entries.entrySet()); 
     list.sort(HIGHEST_VALUE); 
     Collections.reverse(list); 
     return new ArrayList<>(list.subList(0, list.size() < MAXIMUM_WINNERS ? list.size() : MAXIMUM_WINNERS)); 
    } 

    /** 
    * The map containing all of the entries for the week 
    * @return the entries 
    */ 
    public Map<String, Integer> getEntries() { 
     return entries; 
    } 

    /** 
    * The winner of the previous week 
    * @return the winner 
    */ 
    public Collection<Entry<String, Integer>> getWinners() { 
     return winners; 
    } 

    /** 
    * Sets the new winner of the week 
    * @param winner the winner 
    */ 
    public void setWinners(Collection<Entry<String, Integer>> winners) { 
     this.winners = winners; 
    } 

    /** 
    * The date the week started 
    * @return the date 
    */ 
    public Date getDate() { 
     return date; 
    } 

    /** 
    * Sets the date of the week the event starts on 
    * @param date the date 
    */ 
    public void setDate(Date date) { 
     this.date = date; 
    } 

} 
+0

Все ваших нестатических полей должны быть либо временными или Сериализуемыми для сериализатора по умолчанию работать. – Prashant

+0

Коллекция и запись оба не реализуют Serializable, я внесла необходимые изменения в класс. –

+0

сейчас работает? – Prashant

ответ

0

Это не достаточно для класса, который вы пытаетесь сериализации быть Serializable, все, что классы полей должны также быть Serializable. В частности, большинство интерфейсов, включая Collection и Map.Entry, не реализуют Serializable.

При перемещении графика может возникнуть объект, который не поддерживает интерфейс Serializable. В этом случае будет сброшен NotSerializableException и будет идентифицировать класс объекта, не связанного с сериализацией.

Как правило, вы всегда должны использовать явно сериализуемые типы в качестве полей для сериализуемых классов (например, ArrayList, вместо List или Collection), в противном случае вы можете столкнуться с такого рода запутанным неудачи выполнения.

Ваших альтернатив определить метод пользовательского writeObject() для обработки непредоставления Serializable полеев или использовать transient свойство, чтобы указать сериалайзер следует игнорировать это поле.

Подробнее: https://docs.oracle.com/javase/8/docs/technotes/guides/serialization/index.html

Смежные вопросы