我有一点好奇心:
if (!(Outer instanceof Outer.Nested))
{
System.out.println("IT IS NOT THE SAME!!");
}
为什么编译器不理解Outer.Nested
不扩展Outer
而不能成为它的实例,因此会回复编译错误?
请注意,如果它是相反的方式:Outer.Nested instanceof Outer
则不起作用。
答案 0 :(得分:1)
首先,如果Outer
是类类型,则此语句无法编译:
if (!(Outer instanceof Outer.Nested)) // Outer is not an expression: Expression expected
在问题中没有预先设定的上下文,我想你会处理这样的场景:
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
}
}
所有这些都正常发生。
如果您的方案类似:听起来像是编译器进程的问题。
如果您的方案不相似:请使用更多信息更新您的问题。
答案 1 :(得分:1)
来自JLS 15.20.2:
RelationalExpression:
....
RelationalExpression instanceof ReferenceType
instanceof运算符的RelationalExpression操作数的类型必须是引用类型或null类型;否则,发生编译时错误。
换句话说,instanceof的左侧必须是对某个对象或null
的引用。 Outer
看起来像是一个类名,但这些都不是。
您可能正在寻找Class.isAssignableFrom(),它会告诉您一个类是否是另一个类的超类。