0

I'm trying to write a program that will run a method given the code as a string.

Here is an example:

public static void main(String[] args) {
    String code = "public class Test { public static void test() { System.out.println(\"This is a test!\"; } }";

    // somehow load that string as a class

    // then run the method Test.test() and have the results printed

}

If this is possible or has been done before, I'd greatly appreciate a direction to take to achieve this.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Jonah M
  • 1
  • 3
  • Please provide details of What have you tried? – mtk Jul 02 '21 at 15:12
  • 2
    Compiling Java source code to Java byte code at run-time is pretty complex. You may rethink if you really need this. Alternatively you could look at scripting languages like Apache Groovy - they also run in a JVM. – Robert Jul 02 '21 at 15:12
  • Thanks @Robert, it was just an idea of a test I was trying to do. I don't need it for anything specifically other than to see if I was capable of achieving it. – Jonah M Jul 02 '21 at 15:14
  • Please read https://dzone.com/articles/how-to-compile-a-class-at-runtime-with-java-8-and – Robert Jul 02 '21 at 15:18

0 Answers0