Class ClassLoaderUtils
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-UNNAMEDWithout it, the static initializer of this class will fail.
- See Also:
-
Method Summary
Modifier and TypeMethodDescriptionstatic voidappendToSearchPath(@NotNull URLClassLoader classLoader, @NotNull File file) Appends a jar file — or every jar inside a directory tree — to the search path of the givenURLClassLoader, making any classes and resources inside them resolvable through that loader.static booleanTells whetherfileis an existing regular file whose name identifies it as a jar.static booleanisValidJarName(String fileName) Tells whetherfileNamematches the expected naming convention for a jar archive.
-
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 givenURLClassLoader, making any classes and resources inside them resolvable through that loader.If
fileis a directory, its direct children are processed recursively; non-jar entries inside a directory are silently ignored. Iffileis a regular file it must be a jar (seeisJarFile(File)); otherwise anIllegalArgumentExceptionis 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 benullfile- a jar file, or a directory tree to scan for jar files; must not benull- Throws:
IllegalArgumentException- iffileis a regular file but not a jarIllegalStateException- if a directory in the tree cannot be listed
-
isJarFile
Tells whetherfileis an existing regular file whose name identifies it as a jar.- Parameters:
file- file to inspect- Returns:
trueifffileexists as a regular file and its name passesisValidJarName(String)
-
isValidJarName
Tells whetherfileNamematches the expected naming convention for a jar archive. Matching is case-insensitive against the.jarsuffix; the file system is not consulted.- Parameters:
fileName- file name (not a full path)- Returns:
trueifffileNameends with.jar(any case)
-