Java instanceof operator

24,656

Solution 1

What you're doing is not actually the same. Consider what happens with subclasses (I know you can't subclass String, so in the String case it doesn't matter).

class A {}
class B extends A {}

B b = new B();
b instanceof A // true
b.getClass() == A.class // false

If you have an object and you want to know if it is an instanceof a certain type and you have the Class object, you can use the Class#isInstance method.

In either case, I expect performance differences to be insignificant.

Solution 2

There's also

Class<?> classType = String.class;

if (classType.isInstance(s)) {...

As for performance, I'd expect the differences between any of these to be negligible.

Share:
24,656
travega
Author by

travega

Updated on July 11, 2022

Comments

  • travega
    travega almost 2 years

    Is there a valid class Type variable that can be used with the instanceof operator? For Example:

    String s = "abc";
    
    Class<?> classType = String.class;
    
    if (s instanceof classType) {
        //do something
    }
    

    as an alternative to this:

    if (s.getClass() == classType) {
        //do something
    }
    

    Would there be any performance benefit?

  • fernandohur
    fernandohur over 11 years
    so X.class.isInstance(objectX) is faster than doing objectX instanceof X?
  • Jeff Storey
    Jeff Storey over 11 years
    They are different. You use the first if you have the class type, since you can't do objectX instanceof xClass. It helps for dynamic checking when the class you're checking against is unknown at compile time.
  • fernandohur
    fernandohur over 11 years
    I'm not sure I was clear, lets say this: java.lang.String.cass.isInstance(objectX) compared to objectX instanceof java.lang.String. Which would you say is faster?
  • Jeff Storey
    Jeff Storey over 11 years
    I would guess off hand that instanceof is since it's a built-in java construct, but you could run some tests to find out.
  • Ricardo Rivaldo
    Ricardo Rivaldo over 10 years
    b.getClass() = A.class // false should be b.getClass() == A.class // false (== instead of =)