devoured elysium
devoured elysium

Reputation: 105067

Instantiating a class and running its methods in a different JVM

Let's say I have a class X with a no-arg constructor and a method m that I need to run in a fresh new JVM for wizardry purposes.

My first thought lay in calling it from the command line (org.apache.commons.exec.CommandLine) but now I'm stuck with the fact that X doesn't have a main() method (I'm assuming the only way to call Java code through the command line is passing to java a class that contains a static main method, right?). I can through a quick detour create my own main() method in the calling class, and have as its contents

public static void main(String[] args) {
  String classToInstantiate = args[some index];
  ...
}

but I was wondering if there's some cleaner way to accomplish this.

To recap, I need to know the cleanest way to instantiate an arbitrary class as well as invoke arbitrary methods on that class, on a different JVM than that of my main code.

Thanks

Upvotes: 3

Views: 776

Answers (1)

Rafael Winterhalter
Rafael Winterhalter

Reputation: 43997

With Java 9, a REPL is included within the OpenJDK. This way, you could invoke the code programatically from the console by using this REPL. It might even be ported back to Java 8 in an upcoming update. Today, in Java 8, this is possible with a few distractions by running the Nashorn REPL.

Alternatively, you can write a program that does this job for you or use a REPL that is packaged with other languages for the JVM such as Scala.

Upvotes: 1

Related Questions