Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

java - 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/

I am converting JSON to 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):

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

The QueryValue class had these fields (with getters/setters) perviously:

int id;
String uri;
String name;

I now want to be able to have different types of 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.

double lower;
double upper;

And want to make a new ResourceQueryValue (subclass of QueryValue) which looks the same as QueryValue used to:

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.

If I have not been clear please do let me know.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Gson does not currently have a simple mechanism for polymorphic deserialization, other than implementing custom deserialization processing. The next release looks like it will provide a built-in solution.

Previous StackOverflow.com Questions And Answers (Some With Examples) On This Topic:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...