0

I feel like i have to ask this here because i can not find a proper answer somewhere else. I'm trying to get this following code snippet to work where componentList is a List<Component>. I know some workarounds like the ones mentioned in the comments here. But i just wondered if theres is some kind of expression in java to check for an instanceof of an generic parameter without having an instance of it. I know i could also use an class or some kind of value as an identifier for it.

public <T extends Component> T getComponent(){
        for (Component component:componentList) {
            if(component instanceof T){
                return component;
            }
        }
        return null;
    }

Already thank you for your answers and the spell checking^^

Jonas Re
  • 93
  • 1
  • 1
  • 10

1 Answers1

4

Because of type-erasure, T is unknown at runtime, so you have to pass in a parameter to tell the code at runtime what T is.

public <T extends Component> T getComponent(Class<T> type) {
    for (Component component : componentList) {
        if (type.isInstance(component)) {
            return type.cast(component);
        }
    }
    return null;
}

The caller must then supply the parameter like this:

Subcomponent x = getComponent(Subcomponent.class);

Unfortunately, there is no way around that.

Andreas
  • 154,647
  • 11
  • 152
  • 247
  • 1
    `(T) component` generates a compiler warning. `type.cast(component)` should be used instead. – VGR Mar 11 '20 at 01:49