为什么不能将“类”变量传递给instanceof? [英] Why can't a "Class" variable be passed to instanceof?

查看:113
本文介绍了为什么不能将“类”变量传递给instanceof?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我为什么这个代码不能编译?

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

为什么我不能将类变量传递给 instanceof



提前感谢。

方案

instanceof 操作符适用于引用类型,例如 Integer new Integer(213)。您可能想要像

  clazz.isInstance(obj)






注意:如果写

,代码会更加简洁

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

不过真的不知道你是否需要一个方法。


could anyone tell me why this code won't 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?

Thanks in advance.

解决方案

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.

这篇关于为什么不能将“类”变量传递给instanceof?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆