如何将 java.io.File 转换为 java.lang.Class 来运行它?
我有一个程序,允许用户选择任何 .class
或 .jar
文件并运行它。问题是,要运行它,我需要使用 java.io.File
之外的其他东西,这是 JFileChooser
返回的内容。如何将 java.io.File
转换为 java.lang.Class
或 java.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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您有要加载的类的
File
对象,则可以使用URLClassLoader
来加载该类。File
对象可以提供URL
。If you have a
File
object of the class you want to load, you can use aURLClassLoader
to load the class. TheFile
object can provide theURL
.问题是您需要从类本身推断类路径。这不是最容易做的事情。
最好的选择是使用 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.