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

How can I invoke private method using method handles ?

As far as I can see there are only two kinds of publicly accessible Lookup instances:

MethodHandles.lookup()

MethodHandles.publicLookup()

and neither allows unrestricted private access.

There is the non-public Lookup.IMPL_LOOKUP that does what I want. Is there some public way to obtain it (assuming that SecurityManager allows it) ?

解决方案

Turns out it's possible with Lookup#unreflect(Method) and temporarily making method accessible (potentially introducing small security issue unless done during program initialization).

Here is modified main method from Thorben's answer:

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();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值