简体   繁体   中英

Is it possible to create an instance of parameterized class in Java?

I have the same logic in classes creation, but actual classes are different. Is it possible somehow to create an instance of a parameterized class?

Here is an example:

public class MyClass <E extends MyEntityClass> {
    public List<E> myList = new LinkedList<>();

    public MyClass(JsonArray params) {
        for(JsonElement param : params){
            myList.add(new E(param));
        }
    }
}

MyEntityClass - is the super class which has the constructor which accepts JsonElement.

I know that Java doesn't allow to create the parameterized class, but is it possible to solve somehow this problem?

Generics are erased after compilation.
So of course, instantiating directly a parameterized type as you try to do is not possible.

As workaround, you could pass a factory method to your constructor.

With functional interface, you could add a parameter Function<JsonElement,E> in your constructor and use it to create instances of the generic element :

public class MyClass<E extends MyEntityClass> {
    public List<E> myList = new LinkedList<>();

    public MyClass(JsonArray params, Function<JsonElement, E> factoryE) {
        for(JsonElement param : params){
            myList.add(factoryE.apply(param));
        }
    }
}

And you could instantiate your class in this way :

MyClass<MyEntityClass> myClass = new MyClass<MyEntityClass>(MyEntityClass::new);

With a MyEntityClass defined with a constructor that accepts a JsonElement parameter :

public class MyEntityClass {
    ...
    public MyEntityClass(JsonElement jsonElement){
      ...
    }
   ...
}

Of course, you can achieve the same thing without functional interface but it would be more verbose.

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