聪明的方式检查超级

F. *_* P. 7 java comparison class superclass

public  boolean isUserControled(){      
        return action.getClass().getSuperclass().toString().equals("class logic.UserBehaviour");
}
Run Code Online (Sandbox Code Playgroud)

我认为这段代码非常明显.有更聪明的方法吗?

谢谢

Spe*_*eck 11

(action instanceof logic.UserBehaviour) 如果action是扩展UserBehavior的类型的对象,则返回true.

来自http://download.oracle.com/javase/tutorial/java/nutsandbolts/op2.html的摘录

类型比较运算符instanceof

instanceof运算符将对象与指定的类型进行比较.您可以使用它来测试对象是否是类的实例,子类的实例或实现特定接口的类的实例.

以下程序InstanceofDemo定义了一个父类(名为Parent),一个简单的接口(名为MyInterface),以及一个从父级继承并实现接口的子类(名为Child).

class InstanceofDemo {
  public static void main(String[] args) {

    Parent obj1 = new Parent();
    Parent obj2 = new Child();

    System.out.println("obj1 instanceof Parent: " + (obj1 instanceof Parent));
    System.out.println("obj1 instanceof Child: " + (obj1 instanceof Child));
    System.out.println("obj1 instanceof MyInterface: " + (obj1 instanceof MyInterface));
    System.out.println("obj2 instanceof Parent: " + (obj2 instanceof Parent));
    System.out.println("obj2 instanceof Child: " + (obj2 instanceof Child));
    System.out.println("obj2 instanceof MyInterface: " + (obj2 instanceof MyInterface));
  }
}

class Parent{}
class Child extends Parent implements MyInterface{}
interface MyInterface{} 
Run Code Online (Sandbox Code Playgroud)

输出:

obj1 instanceof Parent: true
obj1 instanceof Child: false
obj1 instanceof MyInterface: false
obj2 instanceof Parent: true
obj2 instanceof Child: true
obj2 instanceof MyInterface: true
Run Code Online (Sandbox Code Playgroud)

使用instanceof运算符时,请记住null不是任何实例.


Mat*_*Mat 9

除非您特别想要检查第一个超类,否则最好使用:

return (action instanceof logic.UserBehavior);
Run Code Online (Sandbox Code Playgroud)

你的方法会更好:

action.getClass().getSuperClass().name().equals("logic.UserBehavior");
Run Code Online (Sandbox Code Playgroud)

打电话toString()不是最好的主意.

或者更好的是,由Ulrik发布:

action.getClass().getSuperClass() == logic.UserBehavior.class
Run Code Online (Sandbox Code Playgroud)


Ulr*_*rik 5

如果您只想检查第一个超类:

return action.getClass().getSuperclass() == logic.UserBehavior.class;
Run Code Online (Sandbox Code Playgroud)

除此以外:

return (action instanceof logic.UserBehaviour);
Run Code Online (Sandbox Code Playgroud)