Search code examples
groovymetaprogrammingabstract-syntax-treeinner-classes

How can I determine whether a nested class is static in a Groovy AST transformation?


In an AST transformation, I am trying to detect whether a class Foo has nested classes and, if so, whether they are static or inner classes:

@MyTransform
class Foo {
  static class A {}
  class B {}
}

When I examine fooCn.innerClasses, both Foo$A and Foo$B are listed. ClassNode includes a method called isStaticClass, but by the Javadoc, this only tells me whether a nested class is declared within a static method (as a local class), not whether it is a "static class" by the JLS definition. Both a.staticClass and b.staticClass return false, and both a and b return Foo for outerClass.

How can I inspect the class nodes for Foo$A and Foo$B and determine that Foo$A is a static nested class?


Solution

  • The ClassNode representing each class has a property modifiers containing the modifier flags for the class; bit 4 (value 8) is defined as the STATIC modifier. The utility method java.lang.reflect.Modifier.isStatic(classNode.modifiers) will indicate whether the class is static nested or inner.