Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gradle - Can't access class fields

Tags:

gradle

groovy

I am creating a gradle plugin in groovy, but I can't access the fields of the class. Here's what I have:

public class MyPlugin implements Plugin<Project> {
  void apply(Project project) {
     project.extensions.create("myClass", MyClass)
     println project.myClass.getClass().getName()
     for(Field field : project.myClass.getClass().getFields()) {
        println field.getName()
        println field.getType()
     }
  }
}

class MyClass {
  @MyAnnotation("Hello world")
  String myFeild
}

Output

MyClass_Decorated
__$stMC
boolean

Expected

MyClass
myField
String
like image 368
CMPS Avatar asked Mar 12 '23 06:03

CMPS


1 Answers

I forget how groovy works... if you don't specify a scope on a field is it public?

Class.getFields() only returns the public fields in the class (and super classes). You might need to use a combination of Class.getDeclaredFields() and Class.getSuperclass() to get the private/protected/default scoped fields all the way up the class hierarchy.

If you don't want to reflect the _Decorated class, you can reference the class directly instead of using the instance.

Eg: MyClass.fields or MyClass.declaredFields in groovy

Or: MyClass.class.getFields() or MyClass.class.getDeclaredFields() in java

like image 52
lance-java Avatar answered Mar 20 '23 07:03

lance-java