Why can't a “Class” variable be passed to instanceof?

后端 未结 4 1816
礼貌的吻别
礼貌的吻别 2020-12-02 17:56

Why doesn\'t this code compile?

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


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-02 18:26

    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.

提交回复
热议问题