Java "serialization method" of anonymous class

Say I'm creating a library that provides, among other things, a priority queue class. The user creates an instance and implements the Comparator interface, which is then gently passed to the priority queue. I want to:

1. give the user the opportunity to easily define the Comparator class - by implementing it as an anonymous class, as shown in this example:

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. Provides the user with the ability to serialize and deserialize the ALONG priority queue using the included comparator.

3. use only JDK for this, other external libraries

Which approach would be best to achieve this?

Currently, I am having problems deserializing the Comparator class, in particular creating an instance of it, since it is private in the class that created it (which "owns") and also does not have a null constructor (this is not a very big problem, so how can I use the available constructors that it provides).

Thanks for any suggestions in advance.

+6
source share
1 answer

Document the class, explaining that for the queue to be serialized correctly, the comparator must be serializable and, preferably, not a non-stationary inner class, as this will also result in the serialization of its surrounding object. Also document the fact that the comparator class should 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 an argument, saves it as part of its internal state, and serializes. FindBugs generates a warning when you pass a non-serializable comparator to the TreeSet constructor.

I do not think you can do better.

+2
source

All Articles