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
?
views:
67answers:
2
+1
A:
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
.
rsp
2010-10-29 21:23:50
I implemented this way: "URLClassLoader ucl = new java.net.URLClassLoader(new java.net.URL[]{files[i].toURI().toURL()});". Now what?
Supuhstar
2010-10-29 21:51:12
@Supuhstar, now you use `ucl` to get a `Class` object via `ucl.loadClass(classname)` and use the class loaded to call a static method or create an object instance. NB, the classname must include the package, as in "java.lang.String".
rsp
2010-10-29 22:00:17
how do i get the class' package info if all I have is the java.io.File of a .class file? I tried "Class<?> thisClass = ucl.loadClass(files[i].getPath());", but got a "java.lang.ClassNotFoundException: J:\Java\Checkers\Checkers.class"
Supuhstar
2010-10-29 22:09:20
@Supuhstar, if your `File` is something like "C:\myProject\com\example\Myclass.class" you must split it into parts "C:\myProject" for the clas path, "com.example" for the package and "Myclass" for the classname. If the user of your application selects the class file and its classpath folder, you should be able to figure it out.
rsp
2010-10-30 09:07:45
That's just it. I DON'T know what the file is gonig to be. The user chooses it.
Supuhstar
2010-10-30 19:16:15
@Supuhstar, so let the user chose both the class file, **and** the classpath folder, then your application can use the 2 points to split the file path in 3 giving all the info you need.
rsp
2010-10-30 19:46:12
A:
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.
MeBigFatGuy
2010-10-31 03:34:45