0

What's the correct syntax to make this work?

public boolean isTypeOf(Class type) {
     return this instanceof type;
}

I intend to call it with:

foo.isTypeOf(MyClass.class);

The method will be overriden, otherwise I would just use instanceof inplace.

Tunaki
  • 132,869
  • 46
  • 340
  • 423
fadedbee
  • 42,671
  • 44
  • 178
  • 308
  • 1
    `this.getClass().equals(type)`? – Thomas Weller Sep 21 '15 at 13:48
  • 3
    Did you know about Class.isInstance(Object)? - http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#isInstance(java.lang.Object) – Injektilo Sep 21 '15 at 13:48
  • 1
    Note that in Java's grammar, an instance of Class is not a type name - it's a value, and there is no way to get a typename from a value, even with generics (for example, in a generic function you can't say `if(someObject instanceof T)`. – Injektilo Sep 21 '15 at 13:53

1 Answers1

8

Use Class.isInstance(obj):

public boolean isTypeOf(Class type) {
     return type.isInstance(this);
}

This method determines if the given parameter is an instance of the class. This method will also work if the object is a sub-class of the class.

Quoting from the Javadoc:

This method is the dynamic equivalent of the Java language instanceof operator.

Tunaki
  • 132,869
  • 46
  • 340
  • 423