Patterns for libraries to access private state of user modules

Gunnar Morling gunnar at hibernate.org
Mon Nov 13 16:03:22 UTC 2017


Hi,

Libraries such as Hibernate often need to access private state of classes
from other modules (e.g. when using field access for JPA entities).

Assuming that such library and the user's JAR are both provided as JPMS
(named) modules, it had been my understanding so far [1], that the library
should allow to pass in a MethodHandles.Lookup instance which has private
access to the user's classes. This could be passed via a parameter during
the library bootstrap, retrieved via a callback or similar.

But discussing this with Alex Buckley at Devoxx Belgium last week, he
suggested that this may not be the best level of abstraction. User code
should never have to deal with low-level APIs such as Lookup, instead some
sort of utility method should be provided by the library. It's not quite
clear to me how this would look like, though. I can't see how a utility
method in my library could obtain the Lookup, as MethodHandles#lookup() is
caller-sensitive and must be invoked from within the module that wishes to
grant private access to the library.

So I'm curious whether there are any recommendations around this. Having
some kind of documented API best practices for library authors in the same
situation as me would be very helpful.

I could also help to write that up, provided there's an agreed on pattern
to do this.

Thanks,

--Gunnar

[1]
http://in.relation.to/2017/04/11/accessing-private-state-of-java-9-modules/#can-you-handle-the-var


More information about the jigsaw-dev mailing list