是否有任何方法可以禁用ORMLite检查使用DataType.SERIALIZABLE声明的字段实现Serializable?

时间:2013-03-28 16:27:32

标签: collections ormlite serializable

问题标题只是说明了一切。我有一个声明如下的字段:

    @DatabaseField(canBeNull=false,dataType=DataType.SERIALIZABLE)
    List<ScheduleTriggerPredicate> predicates = Collections.emptyList();

根据上下文,predicates可以包含空列表或Collections.unmodifiableList(List)返回的不可变列表,其中ArrayList作为参数。因此,我知道所讨论的对象是可序列化的,但是我无法告诉编译器(以及因此ORMLite)它是什么。因此我得到了这个例外:

SEVERE: Servlet /ADHDWeb threw load() exception
java.lang.IllegalArgumentException: Field class java.util.List for field
    FieldType:name=predicates,class=ScheduleTrigger is not valid for type 
    com.j256.ormlite.field.types.SerializableType@967d5f, maybe should be
    interface java.io.Serializable

现在,如果只有某种方法可以禁用支票,那么显然一切都会正常工作......

1 个答案:

答案 0 :(得分:6)

FM中详细记录了定义自定义数据类型:

  

http://ormlite.com/docs/custom-data-types

您可以扩展SerializableType类和@Override isValidForField(...)方法。在这种情况下,这将序列化集合。

public class SerializableCollectionsType extends SerializableType {
    private static LocalSerializableType singleton;
    public SerializableCollectionsType() {
        super(SqlType.SERIALIZABLE, new Class<?>[0]);
    }
    public static LocalSerializableType getSingleton() {
        if (singleton == null) {
            singleton = new LocalSerializableType();
        }
        return singleton;
    }
    @Override
    public boolean isValidForField(Field field) {
        return Collection.class.isAssignableFrom(field.getType());
    }
}

要使用此功能,您必须将dataType替换为persisterClass中的@DatabaseField

@DatabaseField(canBeNull = false,
    persisterClass = SerializableCollectionsType.class)
List<ScheduleTriggerPredicate> predicates = Collections.emptyList();

我已经添加到单元测试中以显示工作代码。这是github change