java - 如何使用反射从外部获取对匿名内部类方法“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());
}
}
}
解决方案
getDeclaredMethod
检索可以执行的方法invoke
:
Method method = inner.getClass().getDeclaredMethod("helloWorld");
method.invoke(inner);
推荐阅读
- node.js - 删除订单有效,删除咖啡无效。相同的功能
- express - 如何使用查找和更新编写 mongo 请求
- firebase - 如何在 Firebase Auth 数据库中注册新用户?
- c# - 将“开箱即用”技能(日历、待办事项等)部署到 Microsoft 虚拟助手
- flutter - 从数据库读取异步时我的列表没有显示
- visual-studio - Xamarin Android 模拟器失败
- swift - URLSession 响应不包含上次重定向的标头
- c# - 有没有办法用某个表中的列名填充组合框?
- python - 如何用熊猫列中的另一个字符串替换子字符串
- javascript - 使用 Vue 存储已编辑的表单字段以供提交