我在 Kryo 遇到了一个奇怪的问题。我可以序列化一个泛型类(如 List)就好了。我什至可以序列化一个没有泛型字段的泛型类。但是,如果我用泛型字段序列化一个泛型类,它就会失败。一个例子应该显示问题。
这是我要序列化的类:
import java.util.ArrayList;
public class GenericClass<T>
{
private final ArrayList<T> list;
public GenericClass()
{
list = new ArrayList<T>();
}
}
这是测试它的代码。第二次调用 writeClassAndObject() 会引发异常。ArrayList 的写入只是为了证明它可以正常工作。
public void testWhySoDumb()
{
File s = Environment.getExternalStorageDirectory();
String dir = s.getAbsolutePath() + "/pagetest";
String fileLocation = dir + "/filetest";
new File(dir).mkdirs();
Output output = null;
Kryo kryo = new Kryo();
kryo.setAsmEnabled(true);
kryo.setDefaultSerializer(CompatibleFieldSerializer.class);
// Test writing ArrayList (this works)
List<Integer> arrayList = new ArrayList<Integer>();
try
{
output = new Output(new FileOutputStream(fileLocation));
kryo.writeClassAndObject(output, arrayList);
}
catch (Exception e)
{
System.out.println(e.getMessage()); // No problem here
}
finally
{
if (output != null)
{
output.close();
}
}
// Test writing GenericClass (this does NOT work)
GenericClass<Integer> genericClass = new GenericClass<Integer>();
try
{
output = new Output(new FileOutputStream(fileLocation));
kryo.writeClassAndObject(output, genericClass); // throws exception!!! <------
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
finally
{
if (output != null)
{
output.close();
}
}
}
我得到以下异常:
com.esotericsoftware.kryo.KryoException: java.lang.IllegalArgumentException: type cannot be null.
Serialization trace:
list (com.myapp.page.history.GenericClass)
at com.esotericsoftware.kryo.serializers.ObjectField.write(ObjectField.java:82)
at com.esotericsoftware.kryo.serializers.CompatibleFieldSerializer.write(CompatibleFieldSerializer.java:42)
at com.esotericsoftware.kryo.Kryo.writeClassAndObject(Kryo.java:624)
at com.myapp.page.history.TestGenerics.testWhySoDumb(TestGenerics.java:57)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:555)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1837)
Caused by: java.lang.IllegalArgumentException: type cannot be null.
at com.esotericsoftware.kryo.Kryo.isFinal(Kryo.java:1135)
at com.esotericsoftware.kryo.serializers.CollectionSerializer.setGenerics(CollectionSerializer.java:60)
at com.esotericsoftware.kryo.serializers.ObjectField.write(ObjectField.java:60)
... 15 more
非常奇怪的是,如果我将“list”的类型从“ArrayList”更改为“T”,它就可以正常工作。Kryo 似乎不知道如何处理 ArrayList 字段。我正在使用 Kryo 3.0.0 版。
谢谢!