java - Compile class while running and use it -
i want make interactive program allows users change behaviour of 1 method while program running. user should able change between
public int result(){ and }.
then, program should able access method , needs do.
is possible in java? heard classloader, unable find tips how use it.
you can use java runtime compiler takes code in string, compiles memory , loads current classloader or 1 of choice.
here hello world program
 string classname = "mypackage.myclass";  string javacode = "package mypackage;\n" +                   "public class myclass implements runnable {\n" +                   "    public void run() {\n" +                   "        system.out.println("\"hello world\");\n" +                   "    }\n" +                   "}\n";  class aclass = compilerutils.cached_compiler.loadfromjava(classname, javacode);  runnable runner = (runnable) aclass.newinstance();  runner.run(); in case string needs like
 string codeinmethod = ....  string javacode = "package mypackage;\n" +                    "public class myclass implements returnsint {\n" +                    "    public int result() {\n" +                    codeinmethod +                    "    }\n" +                    "}\n"; you need create interface implement way of calling instance of class once created. (or use reflection shame)
note: should code trust otherwise code can machine.
Comments
Post a Comment