Ask Your Question
0

How to retrieve the file path of all loaded jars during runtime in Java 17?

asked 2023-06-01 16:30:55 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-06-01 16:46:01 +0000

scrum gravatar image

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>.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-01 16:30:55 +0000

Seen: 7 times

Last updated: Jun 01 '23