I am calling MethodCall.invoke
and attempting to invoke an inaccessible method (the method is declared to be package private) on an object.
If I were using reflection, I could do theMethod.setAccessible(true)
and then access checks would be disabled.
As a hack, I know that MethodDescription
inherits from ByteCodeElement
which defines isAccessibleTo(TypeDescription)
. I overrode that to return true
just to see what would happen. Unsurprisingly, I get an IllegalAccessError
at method invocation time. This also happens if I override isVisibleTo(TypeDescription)
.
I know that the magic of setAccessible(true)
is achieved partially by subclassing MagicAccessorImpl
. I also know this is in the jdk.internal.reflect
package which is not exported by default and which cannot be exported if you're using --release
with javac
, which I am.
Anyway it occurred to me that ByteBuddy may have some facility for performing the same kind of unchecked bytecode work that MethodAccessorGenerator
does.
How can I achieve this with ByteBuddy?
This is not possible as you cannot legally express it in Byte Code. I'd also recommend against using the magic accessor as this does no longer work in future Java versions where this is solved using MethodHandle
s. You can resolve a method handle and invoke it from a generated class.