java - 从子类获取父类

标签 java inheritance

我有一个接受单个参数的方法。该参数可以是任何类 A、B、C 或 D,它们都继承自同一父类 E。但是,我不知道父类的名称(也许是“E”,也许是“F”)。

我希望我的方法接受父类作为参数,这样我就可以传入一个子对象(因此我只需要该方法的一个实现)。

如何找到父类的名称?它位于一个 jar 中,我无法访问源代码。

编辑

方法示例:

private void processResults(final ???parentClassName??? aParentClassName) {
    ...
}

最佳答案

尝试使用 Class#getSuperclass()

Returns the Class representing the superclass of the entity (class, interface, primitive type or void) represented by this Class.

  • If this Class represents either the Object class, an interface, a primitive type, or void, then null is returned.

  • If this object represents an array class then the Class object representing the Object class is returned.

示例代码:

A.class.getSuperclass().getName()

aObject.getClass().getSuperclass().getName()

关于java - 从子类获取父类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24743836/

相关文章:

c++ - 在 STL vector 的派生类中实现 move 语义

java - HashMap值发送到bean类java

java - 难以理解链式哈希表的实现

java - 启用 Websphere 安全性后 Arquillian 测试停止工作

c++ - 事件处理继承 (C++)

java - 在java方法重写中使用通配符

java - 如何抛出除以 0 的异常?

java - 如何从列表 <object> 中删除重复项

JavaScript 原型(prototype)继承不起作用

C++如何检查两个类是否来自同一个对象