java - 检查父类(super class)的智能方法

标签 java class comparison superclass

public  boolean isUserControled(){      
        return action.getClass().getSuperclass().toString().equals("class logic.UserBehaviour");
}

我认为这段代码是不言自明的。有没有更聪明的方法来做到这一点?

谢谢

最佳答案

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

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

The Type Comparison Operator instanceof

The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

The following program, InstanceofDemo, defines a parent class (named Parent), a simple interface (named MyInterface), and a child class (named Child) that inherits from the parent and implements the interface.

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{} 

输出:

obj1 instanceof Parent: true
obj1 instanceof Child: false
obj1 instanceof MyInterface: false
obj2 instanceof Parent: true
obj2 instanceof Child: true
obj2 instanceof MyInterface: true

使用 instanceof 运算符时,请记住 null 不是任何对象的实例。

关于java - 检查父类(super class)的智能方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5523954/

相关文章:

java - 在 Java 和 Android 中通过套接字获取服务器响应

java - InputStream in.read() 的行为与预期不同

java - Java 中的 NFA 模拟

python - 使用来自其他 Cython 代码的自定义 Cython 代码

c++ - OutputIterator 到底是什么以及如何构建一个用于 CGAL Kd_tree::search 的?

javascript - 如何使用 jQuery 读取/写入外部定义的 css 类元素的值?

c# - 比较两个对象的不同属性值

java - 带有 Calendar.after 的 While 语句未启动

java - 显示 Java 中与 2 个线程同步的用法

python - 比较嵌套列表的相似度