2

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. Commented Mar 24, 2013 at 15:11

1 Answer 1

4

Should be:

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

or, which is virtually the same:

if (listener.type ().isAssignableFrom (obj.getClass ()))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.