You can use the following code to retrieve the file path of all loaded jars during runtime in Java 17:
public static List<String> getLoadedJarFilePaths() {
List<String> jarFilePaths = new ArrayList<>();
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
if (classLoader instanceof URLClassLoader) {
URLClassLoader urlClassLoader = (URLClassLoader) classLoader;
for (URL url : urlClassLoader.getURLs()) {
if (url.getProtocol().equals("file")) {
String jarFilePath = url.getPath();
if (jarFilePath.endsWith(".jar")) {
jarFilePaths.add(jarFilePath);
}
}
}
}
return jarFilePaths;
}
This code retrieves the system class loader and checks if it's an instance of URLClassLoader
. If it is, it retrieves the URLs and filters for those that are files and end with .jar
. Finally, it returns the list of jar file paths as a List<String>
.
Asked: 2023-06-01 16:30:55 +0000
Seen: 7 times
Last updated: Jun 01 '23