简体   繁体   中英

Is it possible to compare two different Classes in java?

I have two classes Class1 and Class2, Class1 obj; Class2 obj1; How can I compare obj is instance of Class2 ? I am not able to use instanceOf operator for these classes, It is giving compilation error "cant't compare incompatiable types"

If it's failing at compile time, you can be sure that it would always fail at run time. The compiler won't allow you to use instanceof on two types where the first can't be an instance of the second. eg:

Integer i = 5;
if (i instanceof String) {
    System.out.println("Never happen");              
}

The compiler knows definitively that an Integer can never be a String because they're not in the same inheritance hierarchy. Therefore it won't even let you write it. If you're tempted to write it anyway, then there's something wrong with your design and/or your logic.

That being said, Class.isAssignableFrom() is another way to check inheritance hierarchies that can only fail at runtime:

Integer i = 5;
if (String.class.isAssignableFrom(i.getClass())) {
    System.out.println("Never happen");
}

It bears repeating that, while the above will compile successfully, the condition still can never be true. It only makes sense to compare types when they're in the same inheritance hierarchy. For instance, this is a sensible comparison to make:

Number n = 1;
if (n instanceof Integer) {
    System.out.println("I'm an int!");
} else if (n instanceof Long) {
    System.out.println("I'm a long!");
}

If you're tempted to write code like this, though, it almost always means that you've broken polymorphism in your code, since this is exactly the sort of thing it's supposed to handle.

This is not going to compile:

String s = "42";
if (s instanceof Integer) {
    ....
}

but this will:

String s = "42";
Object o = s;
if (o instanceof Integer) {
    ....
}

The thing to understand is that the compiler is using the declared types of the expressions when doing static type checking. In the first case, s has type String and a String cannot ever be an Integer . In the second case, o has type Object and something that is assignable to Object could be an Integer . (Of course, the test in the second example will always evaluate to false ... because the actual instance that o refers to is not an instance of Integer or a subtype.)

Sorry, but if i am not wrong, you are spelling and writing the word incorrectly..

Its instanceof , NOT instanceOf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM