how can i write this code in java?
public class ComponentsManager
{
private List<IComponent> list = new ArrayList<IComponent>();
public <U extends IComponent> U GetComponent() {
for (IComponent component : list) {
if(component instanceof U)
{
return component;
}
}
}
}
but i cant perform instanceof on generic types. how should i do it?
thanks.
Basically you can’t do that due to type erasure. The normal workaround is to pass a
Classobject as a parameter; e.g.You could also use
if (clazz.equals(component.getClass())) { ...but that does an exact type match … which is not what theinstanceofoperator does. Theinstanceofoperator and theClass.instanceOfmethod both test to see if the value’s type is assignment compatible.