如何将 java.io.File 转换为 java.lang.Class 来运行它?

发布于 2024-09-30 00:54:05 字数 254 浏览 0 评论 0原文

我有一个程序,允许用户选择任何 .class.jar 文件并运行它。问题是,要运行它,我需要使用 java.io.File 之外的其他东西,这是 JFileChooser 返回的内容。如何将 java.io.File 转换为 java.lang.Classjava.util.jar.JarFile

I have a program that lets a user select any .class or .jar file and run it. The problem is that, to run it, I need to use something other than a java.io.File, which is what a JFileChooser returns. How can I make a java.io.File into a java.lang.Class or java.util.jar.JarFile?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

旧瑾黎汐 2024-10-07 00:54:05

如果您有要加载的类的 File 对象,则可以使用 URLClassLoader 来加载该类。 File 对象可以提供URL

If you have a File object of the class you want to load, you can use a URLClassLoader to load the class. The File object can provide the URL.

神回复 2024-10-07 00:54:05

问题是您需要从类本身推断类路径。这不是最容易做的事情。

最好的选择是使用 asm.objectweb.org 等工具解析文件,找到类的包,并根据类的包和文件名的组合推断类路径根。即使如此,您仍假设此类仅使用该文件目录中的类。

The problem is you need infer the classpath from a class itself. This isn't the easiest thing to do.

Your best bet is to parse the file using a tool such as asm.objectweb.org, and find the package of the class and infer the classpath root from the combination of the class's package and the filename. Even then, you are assuming that this class only uses classes in this one files directory.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文