Search code examples
javacompilationon-the-fly

Java - let user write own code, then compile it, then use it within same runtime


I need to perform following steps:

  1. Let user write own code - no problem, it's just one interface to implement and I save a file
  2. Compile it - no problem, I used ToolProvider.getSystemJavaCompiler() and created .class file
  3. Let user use this new code - here I am stuck. I have .class file and now what? I need somehow add it in my project and I don't know how.

Thanks for help!


Solution

  • Use a URLClassLoader to load the classes. Then you can use reflection to instantiate and manipulate them.