Combining MethodHandles.publicLookup () with Method.setAccessible (true)
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");
m.setAccessible(true);
MethodHandle mh = MethodHandles.publicLookup().unreflectGetter(m);
char[] ch = (char[])mh.invoke("hello");
Arrays.fill(ch, '*');
System.out.println("hello");
source to share