[Solved] Returning specific type of Object that extends Object?

	public Component findComponentOfType(Class<? extends Component> componentType){
		
		Component thisComponent = null;

		for(int i = 0; i < components.size(); i++){
			if(components.get(i).getClass().equals(componentType)){
				thisComponent = components.get(i);
			}
		}
		

		return (componentType.cast(thisComponent));
}

I’m trying to convert thisComponent to the same type of componentType and return it to use as componentType in another method. They both extend the same class which is Component.
I’m assuming it has something to do with me not knowing how to make my method as generic as possible. Any ideas?

public Component findComponentOfType

This ought to work:



public <T extends Component> T findComponentOfType(Class<T> componentType){


@SuppressWarnings("unchecked")
	public <T extends Component> T findComponentOfType(Class<T> componentType){
		
		Component thisComponent = null;

		for(int i = 0; i < components.size(); i++){
			if(components.get(i).getClass() == componentType){
				thisComponent = components.get(i);
			}
		}
		

		return (T) thisComponent;
		
}

Thanks that lets me use it in the other method! Problem now is that my code is only giving me null objects. Not because of your solution of course. :emo:

I’m an idiot, my problem is elsewhere. Thank you!

You probably want to stop iterating the loop after you find a matching component.

Cool! I didn’t know you could do that! ;D

You can even return mid loop.


@SuppressWarnings("unchecked")
public <T extends Component> T getComponent(Class<T> klass)
{
    for (Component c : components)
        if (klass.isInstance(c))
            return (T) c; // Is Class#cast better here?

    return null;
}

I’d opt for:

klass.isAssignableFrom(c)

which is the conceptually equal to [icode]c instanceof klass[/icode].

You surely mean: [icode]klass.isAssignableFrom(c.getClass())[/icode]

Ofcourse :persecutioncomplex: