I think you should redesign getComponent
to take a Class<? extends Component>
rather than a Component
. Then you can use isInstance
:
public Component getComponent(Class<? extends Component> componentClass) {
for (Component component : getComponentList()) {
if (componentClass.isInstance(component)) {
return component;
}
}
return null; // Or throw an exception, potentially.
}
And SomeComponent
would use:
appManager.getComponent(SomeComponent.class);
If you really wanted to use an instance, you could overload the method like this:
public Component getComponent(Component existingComponent) {
return getComponent(existingComponent.getClass());
}
EDIT: If you actually only want to check for the exact class, you don't want instanceof
-like behaviour - you just want:
public Component getComponent(Class<? extends Component> componentClass) {
for (Component component : getComponentList()) {
if (componentClass == component.getClass()) {
return component;
}
}
return null; // Or throw an exception, potentially.
}
I would still suggest using this method signature though - it would feel very odd to have to already have an instance of a component in order to find a component of the type you want.