MethodHandles.Lookup.defineResource?

Stephen Colebourne scolebourne at joda.org
Mon Aug 27 21:51:51 UTC 2018


The specific code was written in Java 8 world to create a ClassLoader
containing the resource with a suitable parent (as a test case). The
resource was accessed using ClassLoader.getResources() from a shared
library. Under Java 9 I've had to change ClassLoader.getResources() to
Class.getResource() in the shared library, which means that creating a
new ClassLoader doesn't work for writing the test. (The relevant code
is now untested, which is far from ideal). See the commit here:
https://github.com/OpenGamma/Strata/commit/8f2d4d32630af2981d167418dab78c8e2fc98a64

The reason for this thread is a realisation that
MethodHandles.Lookup.defineClass() allows a class to be pushed into an
existing ClassLoader & Module, but I'm unaware of an equivalent for
resources, and that seems like a gap, regardless of use case.

The reflection/setAccessible comment refers to articles like this:
https://baptiste-wicht.com/posts/2010/05/tip-add-resources-dynamically-to-a-classloader.html

thanks
Stephen

On Mon, 27 Aug 2018 at 07:53, Alan Bateman <Alan.Bateman at oracle.com> wrote:
>
> On 14/08/2018 15:07, Stephen Colebourne wrote:
> > A new method MethodHandles.Lookup defineClass() was added recently.
> > But what about a defineResource? For adding a new resource to the
> > classpath (such as a .txt file). I just needed such a thing, and
> > though undoubtedly rare, all the recommended solutions use reflection
> > and setAccessible().
> >
> It might be useful to expand on your use-case a bit more. It may be that
> you are really just looking to create a ClassLoader that can locate a
> resource that you generate at run-time. Also the mention of core
> reflection and setAccessible isn't clear as they aren't used with resources.
>
> -Alan


More information about the core-libs-dev mailing list