问题
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