Here is javadoc from javax.lang.model.element.ExecutableElement.getSimpleName()
Returns the simple name of a constructor, method, or initializer. For a constructor, the name "init" is returned, for a static initializer, the name "clinit" is returned, and for an anonymous class or instance initializer, an empty name is returned.
Notice the bold part says for a static initalizer
, it implies ExecutableElement
can represent a static initalizer
.
So how can I get static initalizer in annotation processing environment? Further, does it means we could add annotation on static blocks (though we can't until java8)?
You cannot annotate static initialzer. But you can still access it.
All elements are available in the representation, no matter how you access it.
E.g. if you annotate a class, containing static initializer, you'll get it's TypeElement
representation, and you can get all fields, methods, constructors and initializers using getEnclosedElements()
.
In the loop you can test the kind of the element. For static initializer use:
element.getKind() == ElementKind.STATIC_INIT
For instance initializer use
element.getKind() == ElementKind.INSTANCE_INIT
Now an important question is, what exactly you need to achieve. How to use the initializer.
If you access it during annotation processing, you may find, that there is an initializer, but that's pretty much all. E.g. the body representation isn't available.
If you want to inspect initializer's body, you have to use compiler plugin API introduced in Java 8, using TaskListener
.