gpt4 book ai didi

java - GWT 序列化 TreeMap 的排序/比较器

转载 作者:搜寻专家 更新时间:2023-11-01 02:30:43 25 4
gpt4 key购买 nike

我有一个带有 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 可序列化,您需要

  1. 创建自定义顶级类(如

    CaseInsensitiveOrder implements Comparator<..>, Serializable {
    ...
    }
  2. 像您一样创建常量 CASE_INSENSITIVE_ORDER

  3. 为该类创建一个自定义字段序列化程序 (CaseInsensitiveOrder_CustomFieldSerializer),它在 deserialize() 上返回 CASE_INSENSITIVE_ORDER 实例。

关于java - GWT 序列化 TreeMap 的排序/比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10124202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com