我在Kryo上遇到了一个奇怪的问题。我可以很好地序列化泛型类(例如列表)。我甚至可以序列化没有泛型字段的泛型类。但是,如果我使用泛型字段序列化泛型类,它将失败。应该有一个示例来显示问题。
这是我想要序列化的类:
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
非常奇怪的是,如果我将"列表"的类型从"ArrayList"更改为"T",它可以正常工作。Kryo 似乎不知道如何处理 ArrayList 字段。我使用的是 Kryo 版本 3.0.0。
谢谢!
你是否还有这个问题。我可能会认为这是一个版本问题或特定于Android的东西,因为这应该适用于当前版本。
Kryo kryo = new Kryo();
Output output = new Output(new FileOutputStream("fileLocation"));
kryo.writeObject(output, new GenericClass<String>());