3

我知道这publicLookup()lookup()公共方法更快,我想利用它。如果我要使用MethodHandles.publicLookup().unreflect(Method)一个Method本质上不是公开但我呼吁setAccessible(true)过的东西,它会起作用吗?

4

1 回答 1

5

由于每个人都可以调用已成功调用的 a,因此可以对任何其他对象使用Methodlike使其不被反射。setAccessible(true)MethodHandles.publicLookup()Lookup

毕竟,这是将访问覆盖与MethodHandles 一起使用的唯一方法,因为java.lang.invoke它本身不提供任何访问覆盖功能。

以下演示使用 aField而不是 a Method,但结果令人印象深刻:

Field m = String.class.getDeclaredField("value");
m.setAccessible(true);
MethodHandle mh = MethodHandles.publicLookup().unreflectGetter(m);
char[] ch = (char[])mh.invoke("hello");
Arrays.fill(ch, '*');
System.out.println("hello");
于 2014-09-19T17:42:49.883 回答