user1432980 user1432980 - 1 year ago 86
Java Question

java processing order of annotation and static blocks

What is processed earlier -

block or

For example what is the order of processing the class like this

class TemplateClass {
static {}

where class has some

Answer Source

Those are processed in different ways so there is no specific order. Annotations are just kept in the class metadata (reflection) and need to be accessed via reflection code while static blocks are executed when the class itself is loaded by the classloader. That said reflection can only access the annotation after the class has been loaded and thus you could say the static block is executed first (unless you're doing some evil reflection stuff in it, in which case I'm not sure what would happen - you might even break the application - and every time you do such a thing a kitten dies ;) ).

As an example consider this which is how you could "process" the annotation:

TemplateClass.class.isAnnotationPresent( CustomAnnotation.class );

Here TemplateClass will first be loaded if it hasn't already and during that the static block will be executed. Then, after you get access to the loaded class object, the annotation is "processed" by checking whether it exists on that class and taking appropriate action.

Edit: as commented by @fabian you could execute the line above inside the static block and it should work. That said the more correct answer probably is: the static block will still be executed first but execution won't finish until the annotation has been "processed".

There is one way to "process" annotations before the static block, however: they can be processed at compile time by an annotation processor or even the compiler, if it knows about those annotations. @Deprecated would be an example of this.

That said when and how annotations are processed does not depend on the annotation itself but on the code that uses it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download