1

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?

3
  • 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. Commented Mar 19, 2013 at 20:32
  • You can't unless your .jar file is actually a Java compiler. Commented 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. Commented Mar 19, 2013 at 20:45

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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?
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).
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 :)
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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.