如何从classloader获取classpath? [英] How to get classpath from classloader?

查看:647
本文介绍了如何从classloader获取classpath?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一些第三方代码,当给出'-classpath'命令行参数时,不设置java.class.path,而是只创建一个类加载器,在命令行指定的类路径中添加项目的所有url到类加载器,然后将其设置为上下文类加载器。
在我编写的这段代码的插件类中,我得到了这个类加载器的一个实例,并且不知何故需要用它来获取底层的类路径,这样我就可以在JavaCompiler.getTask的调用中使用它了。 (...)并动态编译其他代码。
但是无论如何似乎没有从ClassLoader获取ClassPath,并且由于java.class.path未设置,我似乎无法访问最初调用应用程序的底层类路径。 。任何想法?

I am using some third party code which when given a '-classpath' command line argument doesnt set the java.class.path, but instead just creates a classloader, adds all the urls for the items on the command line specified classpath to the classloader, and then sets it to be the context classloader. In a plugin class to this code that I have written, I get an instance of this classloader, and somehow need to use it to get back the underlying classpath, so that I can use it in an invocation of JavaCompiler.getTask(...) and compile some other code on the fly. However there doesn't seem to be anyway to get the ClassPath from the ClassLoader, and as java.class.path is unset, I can't seem to access the underlying classpath that the application was initially invoked with...Any ideas?

推荐答案

如果类加载器使用URL,则必须是 URLClassloader 。你有权访问的是为其定义类路径的URL及其父 ClassLoader

If the classloader uses URLs, it must be a URLClassloader. What you have access to is the URLs which defines the classpath for it along side with its parent ClassLoader.

要获取URL,只需执行以下操作:

To get the URLs, simply do the following:

((URLClassLoader) (Thread.currentThread().getContextClassLoader())).getURLs()

这篇关于如何从classloader获取classpath?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆