Avoiding sun.misc.Unsafe and embracing modules in Java libraries: missing links

Peter Levart peter.levart at gmail.com
Fri Apr 13 06:48:10 UTC 2018

On 04/12/18 10:40, Alan Bateman wrote:
> On 11/04/2018 21:07, Rafael Winterhalter wrote:
>> I do not think that this is possible. If the module containing the 
>> interface does not open a package, I cannot change the privileges of 
>> the main module such that I can resolve a method handle for invoking 
>> the special invocation.
>> I just tried this out too and I did not find a way, could you suggest 
>> how to change my code for being able to do so?
> If the interface is public in an exported package (no need for the 
> package to be open) then the proxy will be generated into the unnamed 
> module. So easy to get a Lookup to the proxy class and you can use 
> this as the special caller. Can you change your invocation handler to 
> the following and try it:
> Class<?> proxyClass = proxy.getClass();
> Main.class.getModule().addReads(proxyClass.getModule());
> Lookup lookup = MethodHandles.privateLookupIn(proxyClass, 
> MethodHandles.lookup());
> MethodType mt = MethodType.methodType(String.class);
> return lookup.findSpecial(iface, "foo", mt, 
> proxyClass).bindTo(proxy).invokeWithArguments();
> -Alan

This works logically, but performance wise I would 1st create a proxy 
class, lookup the direct method handles I want to invoke, transform them 
to take Object 'proxy' instance as 1st argument and the rest of 
arguments as an Object[] and return an Object. I would cache the 
resulting MHs in the specific (constant if possible) InvocationHandler. 
Each invocation would then only select the right cached MH as quickly as 
possible and do return mh.invokeExact(proxy, args);


More information about the jigsaw-dev mailing list