简体   繁体   English

如何通过反射 api 从 java 将值注入 groovy 脚本中的字段?

[英]How to inject value into field in groovy script from java via reflection api?

Very simple groovy script:非常简单的 groovy 脚本:

@Field
List list

def execute(Object args) {
    return list[0]
}

I try to write simple code in java:我尝试在 java 中编写简单的代码:

final GroovyClassLoader groovyClassLoader = new GroovyClassLoader();
final File file = new File("<path to groovy file>");
GroovyCodeSource groovyCodeSource = new GroovyCodeSource(file);
final Class groovyClass = groovyClassLoader.parseClass(groovyCodeSource);
final List<String> testList = Collections.singletonList("test");
final Binding context = new Binding();
context.setVariable("list", testList );
final Script script = InvokerHelper.createScript(groovyClass, context);
final Field list = groovyClass.getField("list");
list.setAccessible(true);
list.set(null, testList );
final Object returnValue = script.invokeMethod("execute", null);

But in field groovyClass.getField("list");但在字段 groovyClass.getField("list"); I get exception NoSuchFieldException Could you please help me?我得到异常 NoSuchFieldException 你能帮帮我吗? Why is it happened?为什么会这样?

Based on what was written in the original code, I assume that the default visibility of a field in Groovy is private ;根据原始代码中的内容,我假设 Groovy 中字段的默认可见性是private otherwise the call to list.setAccessible(true) would be redundant, if not obsolete.否则对list.setAccessible(true)的调用将是多余的,如果不是过时的话。

But the Javadoc for Class::getField(String) says "Returns a Field object that reflects the specified public member field of the class or interface represented by this Class object." But the Javadoc for Class::getField(String) says "Returns a Field object that reflects the specified public member field of the class or interface represented by this Class object."

From that I would guess that changing the code like below should do the job:从那我猜想像下面这样更改代码应该可以完成这项工作:

…
final Script script = InvokerHelper.createScript(groovyClass, context);
final Field list = groovyClass.getDeclaredField("list");
list.setAccessible(true);
…

See the respective Javadoc .请参阅相应的 Javadoc

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

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