I have a factory for creating model instances. The factory provides this method:
public <Model> Model createFromJson(String json, final Class<Model> model) {
Model modelInstance = gson.fromJson(json, model);
((IModel)modelInstance).onCreateFromJson();
return modelInstance;
}
As you can see I cast the instance of the model (previously given as class method parameter) to an interface, so I can call specific methods.
Further the generic return type works nice as well, since the caller must not cast any object. It’s simply enough to call:
MyModel myModel = ModelFactory.getInstance().createFromJson(json, MyModel.class);
But, unfortunately, I can call the factory method with ANY kind of object, like:
Integer myTest = ModelFactory.getInstance().createFromJson(json, Integer.class);
So I would like to define the factory method parameter to be of type IModel. But I can’t figure out how, since I’m passing a class, and not an instance of a Model (IModel).
So, actually I am searching for something like this:
public <Model<? extends IModel>> Model
createFromJson(String json, final Class<Model<? extends IModel>> model)
Can anyone give me advice?
Using
Modelas name for your type parameter is confusing since you also seem to have a class namedModel. Instead useMor some other letter.To specify which class a type must extend you need to use this:
Or using it for your example code: