栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用java.lang.invoke.MethodHandle调用私有方法

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用java.lang.invoke.MethodHandle调用私有方法

事实证明,可以使用Lookup#unreflect(Method)并暂时使方法可访问(除非在程序初始化期间完成,否则可能会引入小的安全性问题)。

这是Thorben的答案的主要修改方法:

public static void main(String[] args) {    Lookup lookup = MethodHandles.lookup();    NestedTestClass ntc = new Program().new NestedTestClass();    try {        // Grab method using normal reflection and make it accessible        Method pm = NestedTestClass.class.getDeclaredMethod("gimmeTheAnswer");        pm.setAccessible(true);        // Now convert reflected method into method handle        MethodHandle pmh = lookup.unreflect(pm);        System.out.println("reflection:" + pm.invoke(ntc));        // We can now revoke access to original method        pm.setAccessible(false);        // And yet the method handle still works!        System.out.println("handle:" + pmh.invoke(ntc));        // While reflection is now denied again (throws exception)        System.out.println("reflection:" + pm.invoke(ntc));    } catch (Throwable e) {        e.printStackTrace();    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/464008.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号