Skip to content

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

Very simple groovy script:

@Field
List list

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

I try to write simple code in 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”); I get exception NoSuchFieldException Could you please help me? Why is it happened?

Answer

Based on what was written in the original code, I assume that the default visibility of a field in Groovy is private; otherwise the call to list.setAccessible(true) would be redundant, if not obsolete.

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.