mardi 17 février 2015

Instantiating a class with a generic type parameter in java

I am trying to write a factory class to return an instance of a class with a generic parameter type. I think this can be done using reflection but I am confused as to how.


Here is an example of what I am trying to do.



public class GenericObjectFactory {

public GenericObject<?> getGenericObject(Class clazz){
// I want to return a new instance here of the generic object with type parameter clazz. So something like this...
return new GenericObject<clazz>();


}


anyone any idea how it's done?


I know I can instantiate clazz with newInstance but I want GenericObject. ie getGenericObject (string.getClass()) would return a new GenericObject < String >();


Sorry this post is a bit rambly. I hope it makes sense. Thanks in advance.


Tracey






Aucun commentaire:

Enregistrer un commentaire