这是一个脑筋急转弯。
我知道这个实际的代码在很多层面上都是可怕的。我的问题不是如何做到这一点(我知道静态初始化块),而是为什么这不起作用,以利于我对 Java 序列化的理解。
为什么这行得通
import java.io.*;
import java.util.*;
class Main {
static Comparator<String> COMPARE_STRING_LENGTH;
static {
class CompareStringReverse implements Comparator<String>, Serializable {
public int compare(String o1, String o2) {
return o1.length() - o2.length();
}
};
COMPARE_STRING_LENGTH = new CompareStringReverse();
}
public static void main(String[] args) throws IOException {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("test.ser"));
out.writeObject(new TreeSet<String>(COMPARE_STRING_LENGTH));
out.close();
}
}
而这
import java.io.*;
import java.util.*;
import java.util.concurrent.Callable;
class Main {
static Comparator<String> COMPARE_STRING_LENGTH = new Callable<Comparator<String>>() {
public Comparator<String> call() {
class CompareStringReverse implements Comparator<String>, Serializable {
public int compare(String o1, String o2) {
return o1.length() - o2.length();
}
};
return new CompareStringReverse();
}
}.call();
public static void main(String[] args) throws IOException {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("test.ser"));
out.writeObject(new TreeSet<String>(COMPARE_STRING_LENGTH));
out.close();
}
}
产量
Exception in thread "main" java.io.NotSerializableException: Main$1