为什么不能“阶级”?变量传递给instanceof?

发布于 2024-08-27 22:54:05 字数 258 浏览 7 评论 0原文

为什么这段代码不能编译?

    public boolean isOf(Class clazz, Object obj){
        if(obj instanceof clazz){
            return true;
        }else{
            return false;
        }
    }

为什么我无法将类变量传递给 instanceof

Why doesn't this code compile?

    public boolean isOf(Class clazz, Object obj){
        if(obj instanceof clazz){
            return true;
        }else{
            return false;
        }
    }

Why I can't pass a class variable to instanceof?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

煮茶煮酒煮时光 2024-09-03 22:54:05

instanceof 运算符适用于引用类型,例如 Integer,而不适用于对象,例如 new Integer(213)。您可能想要类似

clazz.isInstance(obj)

附注:如果您编写“

public boolean isOf(Class clazz, Object obj){
    return clazz.isInstance(obj)
}

不确定是否还需要方法”,您的代码将会更加简洁。

The instanceof operator works on reference types, like Integer, and not on objects, like new Integer(213). You probably want something like

clazz.isInstance(obj)

Side note: your code will be more concise if you write

public boolean isOf(Class clazz, Object obj){
    return clazz.isInstance(obj)
}

Not really sure if you need a method anymore ,though.

浅唱々樱花落 2024-09-03 22:54:05

instanceof 只能与显式类名(在编译时声明)一起使用。为了进行运行时检查,您应该这样做:

clazz.isInstance(obj)

这比 clazz.isAssignableFrom(..) 有一点优势,因为它处理的是 obj = 的情况= null 更好。

instanceof can be used only with explicit class names (stated at compile time). In order to do a runtime check, you should do:

clazz.isInstance(obj)

This has a small advantage over clazz.isAssignableFrom(..) since it deals with the case obj == null better.

很酷又爱笑 2024-09-03 22:54:05

正如其他人提到的,您不能将类变量传递给 instanceof,因为类变量引用 Object 的实例,而 instanceof 的右手> 必须是类型。也就是说,instanceof并不意味着“y是对象x的实例”,它意味着“y是类型X的实例”。如果您不知道对象和类型之间的区别,请考虑:

Object o = new Object();

这里,类型是Object,并且o 是对该类型的对象实例的引用。因此:

if(o instanceof Object)

有效,但

if(o instanceof o)

无效,因为右侧的 o 是一个对象,不是一个类型。

更具体地说,类实例不是类型,它是一个对象(由 JVM 为您创建)。在您的方法中,Class 是一种类型,但 clazz 是一个对象(嗯,对对象的引用)

您需要的是一种将对象与类进行比较的方法目的。事实证明,这很流行,因此它作为类对象的方法提供给您:isInstance()

这是 isInstance 的 Java 文档,它更好地解释了这一点:

public boolean isInstance(Object obj)

确定指定的对象是否与赋值兼容
该类所代表的对象。这个方法是动态的
相当于Java 语言的instanceof 运算符。方法
如果指定的 Object 参数非空并且可以是,则返回 true
转换为该 Class 对象表示的引用类型,无需
引发 ClassCastException。否则返回 false。

具体来说,如果此 Class 对象表示一个已声明的类,则此
如果指定的 Object 参数是以下对象的实例,则方法返回 true
所代表的类(或其任何子类);它返回 false
否则。如果此 Class 对象表示数组类,则此方法
如果指定的 Object 参数可以转换为 true,则返回 true
通过恒等转换或扩展得到数组类的对象
参考转换;否则返回 false。如果这个类对象
代表一个接口,如果该类或任何一个接口,则此方法返回 true
指定 Object 参数的超类实现此接口;
否则返回 false。如果这个 Class 对象代表一个
原始类型,该方法返回 false。

参数: obj - 要检查的对象
返回: 如果 obj 是此类的实例,则返回 true
自: JDK1.1

As others have mentioned, you cannot pass a class variable to instanceof because a class variable references an instance of an Object, while the right hand of instanceof has to be a type. That is, instanceof does not mean "y is an instance of Object x", it means "y is an instance of type X". In case you don't know the difference between an Object and a type, consider:

Object o = new Object();

Here, the type is Object, and o is a reference to the instance of the Object with that type. Thus:

if(o instanceof Object)

is valid but

if(o instanceof o)

is not because o on the right hand side is an Object, not a type.

More specific to your case, a class instance is not a type, it is an Object (which is created for you by the JVM). In your method, Class is a type, but clazz is an Object (well, a reference to an Object)

What you need is an way to compare an Object to a Class Object. It turns out that this is popular so this is provided to you as a method of the Class Object: isInstance().

Here is the Java Doc for isInstance, which explains this better:

public boolean isInstance(Object obj)

Determines if the specified Object is assignment-compatible with the
object represented by this Class. This method is the dynamic
equivalent of the Java language instanceof operator. The method
returns true if the specified Object argument is non-null and can be
cast to the reference type represented by this Class object without
raising a ClassCastException. It returns false otherwise.

Specifically, if this Class object represents a declared class, this
method returns true if the specified Object argument is an instance of
the represented class (or of any of its subclasses); it returns false
otherwise. If this Class object represents an array class, this method
returns true if the specified Object argument can be converted to an
object of the array class by an identity conversion or by a widening
reference conversion; it returns false otherwise. If this Class object
represents an interface, this method returns true if the class or any
superclass of the specified Object argument implements this interface;
it returns false otherwise. If this Class object represents a
primitive type, this method returns false.

Parameters: obj - the object to check
Returns: true if obj is an instance of this class
Since: JDK1.1

灰色世界里的红玫瑰 2024-09-03 22:54:05

首先,instanceof要求右侧的操作数是一个实际的类(例如obj instanceof Objectobj instanceof Integer),而不是变量输入。其次,您犯了一个相当常见的新手错误,您确实不应该这样做...以下模式:

if ( conditional_expression ){
    return true;
} else{
    return false;
}

上面的内容可以重构为:

return conditional_expression;

您应该始终执行该重构,因为它消除了多余的 if...else 语句。同样,表达式 return conditional_expression ? true : false; 可重构为相同的结果。

Firstly, instanceof requires that the operand on the right is an actual class (e.g. obj instanceof Object or obj instanceof Integer) and not a variable of type Class. Secondly, you have made a fairly common newbie mistake that you really should not do... the following pattern:

if ( conditional_expression ){
    return true;
} else{
    return false;
}

The above can be refactored into:

return conditional_expression;

You should always perform that refactoring, as it eliminates a redundant if...else statement. Similarly, the expression return conditional_expression ? true : false; is refactorable to the same result.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文