开发者

Programmatically running a Java program

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.


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.


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();


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜