Is there any way to disable ORMLite's check that a field declared with DataType.SERIALIZABLE implements Serializable?

房东的猫 提交于 2019-11-30 00:00:48

问题


Question title just about says it all. I have a field declared like this:

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

Depending on context, predicates can either contain the empty list or an immutable list returned by Collections.unmodifiableList(List) with an ArrayList as its parameter. I therefore know that the object in question is serializable, but there is no way I can tell the compiler (and therefore ORMLite) that it is. Therefore I get this exception:

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

Now, if there was just some way of disabling the check, everything would obviously work fine...


回答1:


Defining a custom data type is pretty well documented in the FM:

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

You can extend the the SerializableType class and @Override the isValidForField(...) method. In this case, this will serialize collections.

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());
    }
}

To use this you must replace the dataType with persisterClass in @DatabaseField:

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

I've added to the unit test to show working code with this. Here's the github change.



来源:https://stackoverflow.com/questions/15687160/is-there-any-way-to-disable-ormlites-check-that-a-field-declared-with-datatype

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!