简体   繁体   English

您可以使用 Java 反射在运行时定义和调用方法吗?

[英]Can you use Java reflections to define and invoke a method at runtime?

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?或者有不同的方法吗?

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. JDK 仍然内置了 JavaScript 引擎,但您可以轻松添加 3rd 方引擎。 If you really want Java to be the language used in the dynamic scripts, one idea is to use JShell script engine wrapper .如果您真的希望 Java 成为动态脚本中使用的语言,一种想法是使用JShell 脚本引擎包装器

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. BeanShell或 Groovy 是其他类似 Java 的选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM