user2071938
user2071938

Reputation: 2265

Generic static Method in Java

I want a generic method which fills a List with objects which are inherite from the class Element My code look like this:

public static <T extends Element> List<T> getElement(ElementType type){
   List<T> elements = new ArrayList<>();
   switch(type){
        case LIGHT:
            elements.add(new Light(id,bezeichnung,beckhoffVars, false));
            break;
        case LIGHTDIM:
            elements.add(new LightDim(id,bezeichnung,beckhoffVars, false, 0));
            break;
   return elements;
}

But the Compiler says: The method add(T) in the type List is not applicable for the arguments (Light)
The method add(T) in the type List is not applicable for the arguments (LightDim)

Upvotes: 1

Views: 128

Answers (4)

Joeri Hendrickx
Joeri Hendrickx

Reputation: 17445

The type of T is bound at compiletime; so you can't make it differ based on a runtime property. To do this you would have to pass in some sort of factory.

Why not design it as a method in the type instead? Like type.wrapInList()? Or at least type.createInstance(...).

Upvotes: 0

dinesh028
dinesh028

Reputation: 2187

That's obvious Light or LightDim class extends Element. But elements is List of <T>. So, you can type cast like:-

case LIGHT:
    elements.add((T) new Light());
    break;
case LIGHTDIM:
    elements.add((T) new LightDim());
    break;

or you can use

List <? super Element>

or if you know Objects to be added are Element. Can be specific like

List<Element>

Upvotes: 0

damienix
damienix

Reputation: 6763

You already know what types you will get so as suggested use

public static List<Element> getElement(ElementType type) {
    List<Element> elements = new ArrayList<>();
    switch (type) {
        case LIGHT:
            elements.add(new Light());
            break;
        case LIGHTDIM:
            elements.add(new LightDim());
            break;
    }
    return elements;
}  

You use generic List<> by providing type Element of element that you want get, but you don't allow others to use your method in generic way.

Thats why it shouldn't be generic.

Upvotes: 0

user902383
user902383

Reputation: 8640

if you really want to create list of any requred classes, try this

public static <T> List<T> getElement(Class<T> t) {
    List<T> elements = new ArrayList<>();
    return elements;
}

you called this by doing

List<String> list = getElement(Light.class);

you could do switch on name of clas (if i remember from java 7 switch on string is allowed), if i'm wrong you could translate classname to enum.

if you want create single element for your array, then switch statement is not required, you could do this by reflection.

but this is not right way, right way is to create list of type which is shared for all object which you want to use, in your case Element

Upvotes: 1

Related Questions