我有一个带有 TreeMap 的可序列化对象。
Map<String, Dogs> dogsByNames = Maps.newTreeMap(); // guava style
到目前为止,一切都很好。 现在忽略键的大小写是必要的:
Map<String, Dogs> dogsByNames = Maps.newTreeMap(String.CASE_INSENSITIVE_ORDER);
这不起作用,因为 String.CASE_INSENSITIVE_ORDER 不可序列化:
com.google.gwt.user.client.rpc.SerializationException: Type 'java.lang.String$CaseInsensitiveComparator' was not included in the set of types which can be serialized by this SerializationPolicy or its Class object could not be loaded. For security purposes, this type will not be serialized.: instance = java.lang.String$CaseInsensitiveComparator@f26f68
所以我自己创建了一个:
private static abstract class MyComparator<T>
implements
Comparator<T>, // extends Ordering<T> do not work
IsSerializable { // Serializable do not work
}
public static final MyComparator<String> CASE_INSENSITIVE_ORDER = new MyComparator<String>() {
@Override
public int compare(final String left, final String right) {
if (null == left) {
return (null == right) ? 0 : -1;
} else if (null == right) {
return 1;
}
return left.compareToIgnoreCase(right);
}
};
但是还是不行。
怎么了?
解决方案:
protected static class MyOrdering // no-private!!!
extends
Ordering<String>
implements
IsSerializable {
@Override
public int compare(final String left, final String right) {
if (null == left) {
return (null == right) ? 0 : -1;
} else if (null == right) {
return 1;
}
return left.compareToIgnoreCase(right);
}
}
public static final Ordering<String> CASE_INSENSITIVE_ORDER = new MyOrdering();
最佳答案
您创建的 CASE_INSENSITIVE_ORDER 是一个匿名类,无法在 GWT 中序列化。要使其 GWT 可序列化,您需要
创建自定义顶级类(如
CaseInsensitiveOrder implements Comparator<..>, Serializable { ... }
像您一样创建常量
CASE_INSENSITIVE_ORDER
。- 为该类创建一个自定义字段序列化程序 (
CaseInsensitiveOrder_CustomFieldSerializer
),它在deserialize()
上返回CASE_INSENSITIVE_ORDER
实例。
关于java - GWT 序列化 TreeMap 的排序/比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10124202/