Saturday, November 2, 2013

Finding well known resources in the JVM

by Richard Vowles

A lot of people don't seem to know this, but it is actually extremely easy to find resources in the JVM without class path scanning.

Quite a few people use a scanning library or implement one themselves (which given the number and variety of ways you can specify a classpath is always going to miss something out). But if you have a well known resource, then its pretty easy to gather up all instances of it in all of the different jars that make up your application, and this is true if you are using Groovy, Java, Scala, JPython or JRuby (or any of the others, as long as you can get access to a class loader).

Since 1.2 of Java, there has been this method in the ClassLoader interface:

    public Enumeration<URL> getResources(String name) throws IOException;

So all you need to do is call:


for example and all copies of that will be returned. It may not be the most efficient implementation, but it is the most well supported and it comes straight in the JVM, no extra dependencies required.

No comments: