This question already has an answer here:
Scenario:
- I have a private list of type Component (where Component is an abstract class)
- This list has an arbitrary number of varying Component subclasses (where each derived type is unique in that list)
- I want to provide a method that allows the user to find a specific Component of their preference
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?
Aucun commentaire:
Enregistrer un commentaire