Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enforcing java annotations at compile time

Hi : I wanted to make sure that an annotation is present at compile time in a class. Is this possible ? I realize that annoataions are, themselves, classes, so I assume so - but Im just not sure syntactically where and how to enforce/implement such a structure in my classes.

like image 840
jayunit100 Avatar asked Jan 24 '12 03:01

jayunit100


People also ask

What is Java annotation processing?

"Annotation Processing" is a hook into the compile process of the java compiler, to analyse the source code for user defined annotations and handle then (by producing compiler errors, compiler warning, emitting source code, byte code ...). API reference: javax. annotation.

Can annotations be extended?

In Java SE 6, annotations cannot subclass one another, and an annotation is not allowed to extend/implement any interfaces.

What is the use of @interface annotation?

Java Custom annotations or Java User-defined annotations are easy to create and use. The @interface element is used to declare an annotation. For example: @interface MyAnnotation{}

What is @interface annotation in Java?

Annotation is defined like a ordinary Java interface, but with an '@' preceding the interface keyword (i.e., @interface ). You can declare methods inside an annotation definition (just like declaring abstract method inside an interface). These methods are called elements instead.


1 Answers

You can write an annotation processor to run arbitrary logic at compile time.

From an annotation processor, you can do things like check whether a class has a particular structure or member present if a particular annotation exists on that class. They are pretty flexible - for more of an idea of what you can do with them check out the API. They are also supported in major IDEs such as Eclipse and Netbeans.

An introduction to writing an annotation processor is here.

like image 148
prunge Avatar answered Oct 17 '22 20:10

prunge