如何在Java中为gson确定运行时对象的类型
看一下下面的代码,它运行得很好:
MyData myData = new MyData(1, "one");
MyData myData2 = new MyData(2, "two");
MyData [] data = {myData, myData2};
String toJson = gson.toJson(data, MyData[].class);
MyData [] newData = gson.fromJson(toJson, MyData[].class);
MyData 只是一个带有 int 和 String 字段的简单类。这工作得很好。但是,如果类直到运行时才知道怎么办?例如,它可能不是“MyData”,但可能是完全不同的类。我们唯一知道的是类的名称(表示为字符串),该名称先前由发送者使用 Class.forName 确定。
如果对象不是数组,它就可以正常工作,如下所示:
final Class<?> componentType = Class.forName(componentClassName);
context.deserialize(someElement, componentType);
但上述技术不适用于数组。
有什么建议吗?
Take a look at the following code, which works fine:
MyData myData = new MyData(1, "one");
MyData myData2 = new MyData(2, "two");
MyData [] data = {myData, myData2};
String toJson = gson.toJson(data, MyData[].class);
MyData [] newData = gson.fromJson(toJson, MyData[].class);
MyData is just a simple class with int and String fields. This works perfectly fine. But what if the class is not known until runtime? e.g. It might not be "MyData", but could be a completely different class. The only thing we know is the name of the class (represented as a string), which was previously determined by the sender using Class.forName.
It works fine if the object is not an array, like so:
final Class<?> componentType = Class.forName(componentClassName);
context.deserialize(someElement, componentType);
The above technique doesn't work for arrays though.
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的意思是 MyData 将成为通用类型 T 吗?如果是这样,由于 Java 类型擦除,您将无法执行此操作。类型 T 仅在编译时可用。
您可以创建一个如下方法:
Do you mean that MyData would become a generic type T? If so you won't be able to do this due to Javas type erasure. The type T is only available at compile time.
You could create a method like:
来获取对象的类
在 java 中,你可以通过调用From java docs:
,它打印:
In java you can get the class of an object by calling
From java docs:
which prints: