0

I've only read a bit about reflections, so I really don't know much.

I'm looking to build a program (class task) where the user writes a method implementation in a provided text box, which then should be invoked. I was wondering if this can be done using reflections? Or is there a different way?

Jim
  • 133
  • 1
  • 8
  • 2
    No, not really. You "could" use it to call the method, once it's compiled. See [How do you dynamically compile and load external java classes?](https://stackoverflow.com/questions/21544446/how-do-you-dynamically-compile-and-load-external-java-classes/21544850#21544850) for an example of how you could dynamically compile and load a class at runtime – MadProgrammer Jan 08 '20 at 23:06
  • Well, you *can* implement a compiler completely in Java, so this task is solvable with the core API alone, as it all boils down to make a class out of the bytecode, which you can do via [`MethodHandles.lookup().defineClass(…)`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/invoke/MethodHandles.Lookup.html#defineClass(byte%5B%5D)) or by creating a subclass of `ClassLoader` and invoking one of its `defineClass(…)` methods. If you don’t want to implement your own compiler, you have to use the compiler API, which is beyond core Reflection. – Holger Jan 09 '20 at 09:06
  • runtime compiling is a possible action in many languages such as squeak(smalltalk). However, to achieve such a thing in Java is a different thing. maybe before java moved to JIT technique it was easier with an interpreter but anyhow I don't understand how reflection can help you. – Guy Sadoun Jan 18 '20 at 10:33

1 Answers1

0

While it's certainly possible to achieve what's you're describing, it's infinitely easier to use a scripting language for such dynamic expressions. JDK still has a JavaScript engine built-in, but you can add 3rd party engines easily. If you really want Java to be the language used in the dynamic scripts, one idea is to use JShell script engine wrapper.

Either way, the approach would go like this:

//Read the code to evaluate
String scriptCode = ...;

//Init the engine of choice
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript"); //Or "jshell" or whatever

//Add all implicit variable values (if any)
Bindings bindings = engine.createBindings();
bindings.put("variableName", variableValue);

//Execute
engine.eval(scriptCode, bindings));

BeanShell or Groovy are other Java-like options.

kaqqao
  • 12,984
  • 10
  • 64
  • 118