Scenario:
My attempt:
private ArrayList<Component> components = new ArrayList<Component>();
public <T extends Component> T getComponent( T type )
{
for ( Component c : components )
{
if ( c instanceof T )
{
return (T) c;
}
}
return null;
}
The compiler reports the following error on the if statement:
Cannot perform instanceof check against type parameter T. Use its erasure Component instead since further generic type information will be erased at runtime
What is the recommended way to achieve this behavior?
You may want to rely on the Class.isInstanceOf(Object):
for (Component c : components) {
if (type.getClass().isInstance(c)) {
return (T) c;
}
}
Determines if the specified Object is assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language
instanceofoperator.
It would make more sense to provide a Class instance instead of an object:
public <T extends Component> T getComponent(Class<T> type)
{
for (Component c : components) {
if (type.isInstance(c)) {
return (T) c;
}
}
return null;
}
The compiler is pretty clear
Use its erasure Component instead
You can replace the parameter T type with Component c
After that you only have to extract the type of c (it will be an implementation, thus c.getClass() will be a class that extends Component).
Than you should check if the type matches and return the first element.
private ArrayList<Component> components = new ArrayList<Component>();
public <T extends Component> T getComponent( Component component )
{
for ( Component c : components )
{
if ( c.getClass().equals(component.getClass()) )
{
return c;
}
}
return null;
}
I think it should work good.
I hope it helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With