有没有办法禁用ORMLite的检查,用DataType.SERIALIZABLE声明的字段实现Serializable? [英] Is there any way to disable ORMLite's check that a field declared with DataType.SERIALIZABLE implements Serializable?
问题描述
问题标题只是说这一切。我有一个字段声明如下:
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();
根据上下文,谓词
空列表或由 Collections.unmodifiableList(List)
以 ArrayList
作为其参数返回的不可变列表。我因此知道有问题的对象是可序列化的,但没有办法我可以告诉编译器(因此ORMLite),它是。因此,我得到这个异常:
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...
推荐答案
定义自定义数据类型在FM中有很好的文档:
Defining a custom data type is pretty well documented in the FM:
您可以扩展 SerializableType
类和 @Override
方法。 isValidForField(...)
在这种情况下,这将序列化集合。
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());
}
}
要使用此功能,您必须替换<$ c $在 @DatabaseField
中使用 persisterClass
的c> dataType :
To use this you must replace the dataType
with persisterClass
in @DatabaseField
:
@DatabaseField(canBeNull = false,
persisterClass = SerializableCollectionsType.class)
List<ScheduleTriggerPredicate> predicates = Collections.emptyList();
我添加了单元测试来显示工作代码。这是 github更改。
I've added to the unit test to show working code with this. Here's the github change.
这篇关于有没有办法禁用ORMLite的检查,用DataType.SERIALIZABLE声明的字段实现Serializable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!