How do I make a java.io.File into a java.lang.Clas

2019-07-20 16:11发布

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?

2条回答
淡お忘
2楼-- · 2019-07-20 16:51

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.

查看更多
叼着烟拽天下
3楼-- · 2019-07-20 16:53

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.

查看更多
登录 后发表回答