0

Is it possible in java to programmatically run a java program?

For example, having a runnable class loaded and run as a thread?

EDIT

I see that I should have been more precise :)

I've got a .class file that I want to read and run.

The idé is that I have no ide what kind of program it is, only that it is a valid class file. What I want to do is to be able to run the .class file as if I myself had written and compiled it.

2
  • Please, try to be more specific. What exactly you want to be executed? Commented May 19, 2011 at 8:23
  • Of course it is possible but can you be more precise? Do you mean that you have a compiled jar-file that you want to run from a Java-program or what? Try to clarify a bit and if possible with an example. Commented May 19, 2011 at 8:24

3 Answers 3

6

Something like this, maybe?

 new Thread(new Runnable() {
  @Override
  public void run() {
    MyRunnableClass.main(new String[]{});
  }
 }).start();

A runnable class is a normal class with a static main method. We can call that method like any other method. If we do that in a Thread, then we'll have something similiar to what the JVM would do when starting an application.


Full version with reflection:

public static void start(final String classname, final String...params) throws Exception {  // to keep it simple
  final Class<?> clazz = Class.forName(classname);
  final Method main = clazz.getMethod("main", String[].class);    

  new Thread(new Runnable() {
    @Override
    public void run() {
      try {
        main.invoke(null, new Object[]{params});
      } catch(Exception e) {
        throw new AssertionError(e);
      }
    }
   }).start();
}

Use it like

start("com.example.myApp", "param1", "param2");

and it will execute the main method of that class in a new Thread.

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

1 Comment

I don't know what he means by "having runnable class loaded", but I think it indicates reflection.
3

Yes, you can do it through reflection if you want to execute the code within your process.

I haven't tested this code, but it should looks something like this:

Class<? extends Runnable> theClass = 
    Class.forName(fullyQualifiedClassName).asSubclass(Runnable.class);
Runnable instance = theClass.newInstance();
new Thread(instance).start();

Comments

0

I found an interresting artivle on how to do that. See here.

1 Comment

Not exactly what I was looking for, yet still interesting

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.