I want to have a Java program that can read a .CLASS file and run that code, using itself as the .CLASS file's library. Is this at all possible?
-
WTF? For whatever it's worth, a .jar file is nothing but a .zip file with a bunch of classes (and perhaps some other stuff) in it. You can read a .jar with WinZip.paulsm4– paulsm42013-03-19 20:32:38 +00:00Commented Mar 19, 2013 at 20:32
-
You can't unless your .jar file is actually a Java compiler.OscarRyz– OscarRyz2013-03-19 20:33:52 +00:00Commented Mar 19, 2013 at 20:33
-
Take a look at this, in particular this. I've not used it, but I've read that it's possible to compile .java files into .class files through these tools at runtime.MadProgrammer– MadProgrammer2013-03-19 20:45:02 +00:00Commented Mar 19, 2013 at 20:45
Add a comment
|
1 Answer
java.lang.ClassLoader
will help you to load external classes.
java.lang.reflect.Method
will help you to invoke methods of loaded external classes.
Tiny example:
ArrayList<URL> urls = new ArrayList<URL>();
urls.add(new File("/path/to/your.class").toURI().toURL()); //can add several..
ClassLoader cl = new URLClassLoader(urls.toArray(new URL[urls.size()]));
Class<?> c;
c = Class.forName("your.class.name", false, cl); //now you have your class
Method m = c.getMethod("main", String[].class); //now your have your method
m.invoke(null, new Object[] { "argument1", "argument2" }); //now you "run that code"
I did not run anything, i just wrote it to show you some tools that can help you.
5 Comments
Dylan Wheeler
Now let's say that the .class file tries to access methods from the main program. Does your code allow the Class object to utilize these methods?
Gyro Gearless
A good recipe, but IMHO the path must point to the root of the folders hierarchy where the .class files are stored (same principle as when setting classpath). Also for this case it would be easier to create an URL[] right away (as it will contain one and only one element).
Erik Kaju
Gyro: I think i see your point, but i tried to show how you can pick one or some particular class(es). Depends what aims you have :)
Erik Kaju
JavaCoder: I am not sure what you mean. Main program -> will load class -> which in it's turn will call some methods of the program that just has loaded that class? Sounds weird, but definitely not impossible.
Erik Kaju
Well, things are getting better for you - wrong number of arguments exception says clearly what is wrong. If the number of formal parameters required by your underlying method is 0, the supplied args array may be of length 0 or null. It really depends on method you are trying to execute.