Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java "method serialization" of anonymous class

Say I'm creating a library which provides amongst other stuff a priority-queue class. The user instantiates one and implements a Comparator interface which is then passed gently to the priority-queue. I want to:

1. grant the user the possibility to define the Comparator class easily - by implementing it as an anonymous class, just like this example suggests:

    PriorityQueue<int> pq = new PriorityQueue<int>();
    pq.setComparator(new Comparator<int>() {
                @Override
                public int compare(int i1, int i2){
                     if(i1 < i2) return -1;
                     else if(i1 > i2) return 1;
                     else return 0;
                }
             };);

2. grant the user the possibility to serialize-and-deserialize the priority queue ALONG with its attached comparator.

3. use only JDK to achieve this, no other external libraries

What approach would be best to achieve this?

Currently I'm having problems deserializing the Comparator class, more specifically creating an instance of it since it's private within the class that created it (that "owns" it) and it also does not have a null-constructor (this is not really a big problem since I can use the available constructors that it exposes).

Thanks for any suggestions in advance.

like image 529
John Xiba Avatar asked Dec 08 '12 23:12

John Xiba


Video Answer


1 Answers

Document the class, explaining that for the queue to be serialized properly, the comparator should be serializable, and preferrably not an non-static inner class, since this would also cause the serialization of its enclosing object. Also document the fact that the comparator class must be available when deserializing the queue, of course.

java.util.TreeSet has the same "problem" as the one you have: it takes a comparator as argument, stores it as part of its internal state, and it is serializable. FindBugs generates a warning when you pass a non-serializable comparator to a TreeSet constructor.

I don't think you can do better than that.

like image 184
JB Nizet Avatar answered Nov 14 '22 23:11

JB Nizet