Class ClassLoaderUtils

java.lang.Object
net.apartium.cocoabeans.reflect.ClassLoaderUtils

@AvailableSince("0.0.50") public class ClassLoaderUtils extends Object
Helpers for working with ClassLoader instances at runtime.

Currently focused on extending a URLClassLoader's search path with additional jar files. The URLClassLoader#addURL(URL) method this relies on is protected, so it is reached via reflective access resolved once in a class initializer.

Module access: on Java 9+ the reflective access used here requires the java.net package of the java.base module to be opened to the caller, e.g. via the JVM flag

--add-opens java.base/java.net=ALL-UNNAMED
Without it, the static initializer of this class will fail.
See Also:
  • Method Details

    • appendToSearchPath

      public static void appendToSearchPath(@NotNull @NotNull URLClassLoader classLoader, @NotNull @NotNull File file)
      Appends a jar file — or every jar inside a directory tree — to the search path of the given URLClassLoader, making any classes and resources inside them resolvable through that loader.

      If file is a directory, its direct children are processed recursively; non-jar entries inside a directory are silently ignored. If file is a regular file it must be a jar (see isJarFile(File)); otherwise an IllegalArgumentException is thrown.

      Symbolic links are ignored, so cyclic links (a link pointing back into an ancestor) cannot trigger infinite recursion. If a directory cannot be listed (an I/O error, e.g. missing read permission) the failure is surfaced rather than silently ignored.

      Adding a URL only extends what the loader can find later — no class is actually loaded or initialized as a side effect.

      Parameters:
      classLoader - the loader whose search path should be extended; must not be null
      file - a jar file, or a directory tree to scan for jar files; must not be null
      Throws:
      IllegalArgumentException - if file is a regular file but not a jar
      IllegalStateException - if a directory in the tree cannot be listed
    • isJarFile

      public static boolean isJarFile(File file)
      Tells whether file is an existing regular file whose name identifies it as a jar.
      Parameters:
      file - file to inspect
      Returns:
      true iff file exists as a regular file and its name passes isValidJarName(String)
    • isValidJarName

      public static boolean isValidJarName(String fileName)
      Tells whether fileName matches the expected naming convention for a jar archive. Matching is case-insensitive against the .jar suffix; the file system is not consulted.
      Parameters:
      fileName - file name (not a full path)
      Returns:
      true iff fileName ends with .jar (any case)