java - 有没有办法检查一个类是否有一个方法,然后在该对象的一个​​已经存在的实例上调用它?

标签 java reflection

我有一个奇怪的案例,如果可能的话,我想通过反射或一些库来处理。 有没有办法检查类是否有方法,然后在对象的现有实例上调用它?

例如,假设我有:

Foo foo = new Foo();

Foo 有一个 close() 方法。假设我知道很多类都有一个 close() 方法,但由于它们设计不佳并且是我无法重写的遗留问题,我想找到一个通用的解决方案调用一个我知道它们都有的方法,尽管它们不是从基类或接口(interface)继承的。

我想在我的 FooHandling 类中有一个方法,它接受初始化的对象并调用它们的 close() 方法。这些对象绝不会继承自同一个基类,因此它们在本质上完全不同,但都有一个同名的方法。所以,在 FooHandler 中,我想要这样的东西:

void coolGenericClosingMethod(Object o)
{
    // 1) Check via reflection if the class `o` represents contains a `close()`
    // 2) Invoke the method, if it exists, but on the passed in object `o`.
}

那么,是否有一些巧妙的技巧可以让我在已经实例化的对象上使用并且仍然这样做?

最佳答案

Is there a way to check if a class has a method

Class#getMethods()

Returns an array containing Method objects reflecting all the public member methods of the class or interface represented by this Class object, including those declared by the class or interface and those inherited from superclasses and superinterfaces

Class#getMethod(String,Class...)

Returns a Method object that reflects the specified public member method of the class or interface represented by this Class object. The name parameter is a String specifying the simple name of the desired method.

抛出:

NoSuchMethodException - 如果未找到匹配的方法

示例代码:

class Foo {
    public void close() {
        System.out.println("close method is invoked");
    }

}
Foo foo = new Foo();

try {
    Method m = Foo.class.getMethod("close");
    m.invoke(foo);
} catch (NoSuchMethodException e) {
    e.printStackTrace();
}

输出:

close method is invoked

关于java - 有没有办法检查一个类是否有一个方法,然后在该对象的一个​​已经存在的实例上调用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24872107/

相关文章:

java - 检测方法是否在 Java 接口(interface)中声明

java - 将 jTextField 恢复为最后一个有效值

java - 是否可以使用 Commons Beanutils 自动实例化嵌套属性?

java - 如何使用 SQL-lite 数据库检索 android studio 中的单选按钮组

java - 如何在 Spring Boot 中的 application.yml 中添加 GCP(Google Cloud Storage)存储属性

java - 什么可能是 ParameterizedType 的实例?

java - 从通过 servlet 动态上传的 jar 中加载类

java - 检查类是否是列表的实例

使用 AOP 的 Spring MVC 项目中的 Java 反序列化问题

java - 通过将运行时参数传递给 java Reflect 方法进行单元测试