Combining MethodHandles.publicLookup () with Method.setAccessible (true)

I understand that it is publicLookup()

faster than lookup()

for public methods and I would like to use that. If I used MethodHandles.publicLookup().unreflect(Method)

in Method

, which is not public, but I called setAccessible(true)

on, would it work?


source to share

1 answer

Since a Method

, which setAccessible(true)

was successfully called, can be called by everyone, it can be made unreflected using MethodHandles.publicLookup()

as with any other object Lookup


At the end of the day, its only way to use access override with MethodHandle

as java.lang.invoke

does not offer any access override feature.

The following demo uses Field

rather than Method

, but has an impressive result:

Field m = String.class.getDeclaredField("value");
MethodHandle mh = MethodHandles.publicLookup().unreflectGetter(m);
char[] ch = (char[])mh.invoke("hello");
Arrays.fill(ch, '*');




All Articles