Question

Here I have a little curiosity:

if (!(Outer instanceof Outer.Nested))
{
    System.out.println("IT IS NOT THE SAME!!");
}

Why does the compiler not understand that Outer.Nested does not extend Outer and cannot be an instance of it, and therefore give back a compilation error?

Note that if it was the other way round: Outer.Nested instanceof Outer it would not work.

Était-ce utile?

La solution

First, this statement could not compile, if Outer is a class type:

if (!(Outer instanceof Outer.Nested))  // Outer is not an expression: Expression expected

Without no precised context in the question, I imagine you would deal with a scenario like this:

public class Outer {

        private class Inner {
        }

        public static void main(String[] args) {
            Test t = new Test();
            Inner i = t.new Inner();
            System.out.println(i instanceof Test);  //inconvertible types => normal
            System.out.println(t instanceof Inner); // inconvertible types => normal
        }

    }

All happens normally thus.

If your scenario is similar: sounds like an issue with your compiler process.

If your scenario isn't similar: please update your question with more information.

Autres conseils

From JLS 15.20.2:

RelationalExpression:
    ....
    RelationalExpression instanceof ReferenceType

The type of the RelationalExpression operand of the instanceof operator must be a reference type or the null type; otherwise, a compile-time error occurs.

In other words, the left hand side of instanceof must be a reference to some object or null. Outer looks like a class name, which is neither of those things.

You may be looking for Class.isAssignableFrom(), which tells you whether one class is a superclass of another.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top