Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find and return an object of <derived type> in a list of <base type>? [duplicate]

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?

like image 476
Bennett Lynch Avatar asked Dec 11 '25 19:12

Bennett Lynch


2 Answers

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 instanceof operator.

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;
}
like image 89
M A Avatar answered Dec 13 '25 10:12

M A


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

like image 40
nessuno Avatar answered Dec 13 '25 08:12

nessuno



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!