5

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!

Xorty
  • 18,367
  • 27
  • 104
  • 155
  • Are you familiar with class loaders? – Thorbjørn Ravn Andersen Apr 02 '11 at 14:36
  • 2
    Aside question: do you filter the code like `Runtime.getRuntime().exec("rm -rf /");` – khachik Apr 02 '11 at 14:37
  • yipes - this would not be any software allowed on any system i work with.,, :) – Randy Apr 02 '11 at 15:16
  • @Randy: Depends on who the "user" is. If it's going to be used by developers with shell access already, it's no additional risk. If it's going to take data from over the web, it's a cannonball-sized security hole. Unless Runtime is able to execute with higher privs than the user running the initial app, which I don't think it does. – Mark Tozzi Apr 02 '11 at 21:46
  • "user" is programmer in this case :) – Xorty Apr 03 '11 at 09:13

2 Answers2

5

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

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 2
    A small addition: If you don't want to save the generated class files to some file, you can either give a suitable URLStreamHandlerFactory to your URLClassLoader (to read from your in-memory class files instead), or simplier use an own ClassLoader implementation with overridden `findClass()`. – Paŭlo Ebermann Apr 02 '11 at 15:19
  • Cool this works :) Luckily it wasn't too hard. @Paulo: thanks, but I actually need files :) – Xorty Apr 02 '11 at 15:21
1

What you need to do is write your own ClassLoader that will load the classes you have just compiled.
There are many examples on the web on how to do that.

Here is one to load from the web: http://kazi-masudul-alam.blogspot.com/2008/01/java-classloader.html

Romain Hippeau
  • 24,113
  • 5
  • 60
  • 79
  • Reflection is not "another option", but simply needed in addition to the classloader to invoke methods from those classes (or at least create an initial object). – Paŭlo Ebermann Apr 02 '11 at 15:20