Home / Java Patterns and Pitfalls     frequal.com

Reflections Subtype Lookup with OneJar


Looking up subtypes via the Relfections library in a OneJar-packaged app can be frustrating. Running from the IDE, where classes are being loaded from a folder, works fine. When you test from the OneJar JAR file, however, class lookup fails. To fix this you'll need some helper classes and conditional Reflections configuration, as shown below.


First, download the files from this posting to add OneJar support to Reflections.

Next, change your code that constructs the Reflections object to look like the following. Change com.your.package.here and YourSupertypeClass.class to match your codebase.

    URL urlModelClasses = ClasspathHelper.forClass(AbstractBlock.class);
    if (urlModelClasses.toString().startsWith("jar:")) {
      // Special one-jar URL handler breaks normal handling, so only use it if we are running via one-jar
      Vfs.setDefaultURLTypes(Arrays.asList(new OneJarUrlType()));

    Reflections reflections = new Reflections(new ConfigurationBuilder()
            .setScanners(new SubTypesScanner()));

Last modified on 17 Jan 2016 by AO

Copyright © 2020 Andrew Oliver