0

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?

3
  • First idea: Javadoc for Class::getField() says: "Returns a Field object that reflects the specified public member field of the class or interface represented by this Class object." – What is the default visibility for a field in Groovy? Commented Dec 4, 2020 at 21:57
  • Second idea: what will be the output from groovyClass.getFields()? Commented Dec 4, 2020 at 21:59
  • Third idea: What about using Class::getDeclaredField()? Commented Dec 4, 2020 at 22:00

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.