首页 > 解决方案 > 如何使用反射从外部获取对匿名内部类方法“helloWorld”的引用

问题描述

下面是我的示例类。如您所见,我定义了一个类InnerClass,并在 main 方法中创建了它的一个实例。但我没有使用普通声明,而是使用基类中不存在的方法声明了它的匿名内部类。

现在我知道如果我要helloWorld()在 InnerClass 内部声明,那么我可以在通过匿名内部类创建的实例上访问此方法。

但我想知道,是否可以在我的代码中不在基类中声明的情况下调用此方法。我尝试探索反射 API,但没有任何运气

import java.lang.reflect.Method;

public class InnerClass {
int i = 10;

public static void main(String[] args) {
    InnerClass inner = new InnerClass() {
        void helloWorld() {
            System.out.println("Hello");
            System.out.println(this.getClass().getEnclosingMethod());
        }
    };
    System.out.println(inner.getClass().getEnclosingMethod());
    Method[] method = inner.getClass().getDeclaredMethods();

    // Call helloworld method here

    for (Method me : method) {
        System.out.println(me.getName());
    }
}
}

标签: javareflectioninner-classes

解决方案


getDeclaredMethod检索可以执行的方法invoke

Method method = inner.getClass().getDeclaredMethod("helloWorld");
method.invoke(inner);

推荐阅读