简体   繁体   English

我可以实例化一个超类并根据提供的参数实例化一个特定的子类吗

[英]Can I instantiate a superclass and have a particular subclass be instantiated based on the parameters supplied

I am using Google's GSON package http://code.google.com/p/google-gson/ 我正在使用Google的GSON软件包http://code.google.com/p/google-gson/

I am converting JSON to Java. 我正在将JSON转换为Java。

I have this fragment of code where I do the conversion. 我有这段代码片段在其中进行转换。

Gson gson = new Gson();
Type collectionType = new TypeToken<Collection<QueryProperty>>() {}.getType();
Collection<QueryProperty> queryProperties = gson.fromJson(query, collectionType);

My QueryProperty class has these fields (with getters/setters): 我的QueryProperty类具有以下字段(带有getter / setter):

int id;
String uri;
String name;
Set<QueryValue> values;
String selected;

The QueryValue class had these fields (with getters/setters) perviously: QueryValue类以前具有以下字段(带有getter / setter):

int id;
String uri;
String name;

I now want to be able to have different types of QueryValue. 我现在希望能够具有不同types的QueryValue。

I want to add a NumericQueryValue class (subclass of QueryValue), so I can pass in a set of bounds with which to query the db. 我想添加一个NumericQueryValue类(QueryValue的子类),因此我可以传递一组查询数据库的范围。

double lower;
double upper;

And want to make a new ResourceQueryValue (subclass of QueryValue) which looks the same as QueryValue used to: 并想要创建一个新的ResourceQueryValue(QueryValue的子类),该外观与用于以下目的的QueryValue相同:

int id;
String uri;
String name;

Is there anyway I can make this work. 无论如何,我可以做这项工作。 That is have a generic QueryValue class, but have the correct subclass returned depending on the parameters that the JSON supplies. 那是一个通用的QueryValue类,但是根据JSON提供的参数返回了正确的子类。

If I have not been clear please do let me know. 如果我不清楚,请告诉我。

Gson does not currently have a simple mechanism for polymorphic deserialization, other than implementing custom deserialization processing. 除了实现自定义反序列化处理之外,Gson当前还没有用于多态反序列化的简单机制。 The next release looks like it will provide a built-in solution. 下一个版本看起来像它将提供一个内置的解决方案。

Previous StackOverflow.com Questions And Answers (Some With Examples) On This Topic: 上一个StackOverflow.com上有关此主题的问题和解答(带有示例):

听起来好像您需要创建自定义解串器(如果需要检查值),或者实例创建器(如果仅需要基于类型创建实例)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM