Check if a object is a instance of a class (but not a instance of its subclass)

前端 未结 7 1518
天命终不由人
天命终不由人 2020-12-03 04:08

For this example:

public class Foo{}

public class Bar extends Foo{}

....

void myMethod(Foo qux){
   if (checkInstance(qux,Foo.class)){
     ....
   }
}


        
相关标签:
7条回答
  • 2020-12-03 05:14

    you should use instanceof

    if(qux instanceof Foo && !(qux instanceof Bar)) {
        ...
    }
    

    This works with both classes and interfaces, so in most cases it should preferred over .class which does not work with interfaces.

    0 讨论(0)
提交回复
热议问题