2
votes

What I'm trying to do:

Type checking with Java inheritance dynamically. I have two classes: 1) com.example.Event and 2) com.example.TransactionEvent which extends com.example.Event. I have a function Class<?> type which returns the type to check against.

Code:

public class Event{}

public class TransactionEvent extends Event{}

public interface Listener
{
    public Class<?> type();
}

public void checkType(Event obj, Listener listener)
{
    System.out.println(obj.getClass().toString());
    System.out.println(listener.type().toString());

    if (obj.getClass().isInstance(listener.type()))
         System.out.println("yay!");
}

Output:

class com.example.TransactionEvent
class com.example.Event

(no Yay)

Isn't TransactionEvent an instanceof Event since it inherits from it?

1
It inherits under the different erasure. - user2173738

1 Answers

4
votes

Should be:

if (listener.type ().isInstance (obj))

or, which is virtually the same:

if (listener.type ().isAssignableFrom (obj.getClass ()))