简体   繁体   中英

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

I think you need the following:

public <T> GenericObject<T> getGenericObject(){
    return new GenericObject<T>();
}

Example usage:

GenericObject<String> obj = genericObjectFactory.getGenericObject();

Typical clear solution for your problem is the following:

public class GenericObjectFactory {
    public <T> GenericObject<T> getGenericObject(Class<T> clazz){
        return new GenericObject<T>();
    }
}

Since T is erasure, so the new created instance of GenericObject even does not "know" what is the value of its parameter T , you will probably want to pass the clazz to constructor of GenericObject

public class GenericObjectFactory {
    public <T> GenericObject<T> getGenericObject(Class<T> clazz){
        return new GenericObject<T>(clazz);
    }
}

Obviously you have to define such constructor.

EDIT

Here is the usage example:

GenericObjectFactory factory = new GenericObjectFactory();
GenericObject<String> gs = factory.getGenericObject(String.class);
GenericObject<Integer> gs = factory.getGenericObject(Integer.class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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