Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I generate a compile time error based on the type of the field being Annotated

I have written a java annotation that looks like this:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)  // can I further limit this to only fields of type DomainObject?
public @interface Owns {
}

After briefly looking around I couldn't see if there was a way to further limit the usage of this annotation so that only fields of a specific type could be annotated. This annotation is custom to our domain and can only be used on instances of our base domain object class.

Does anyone know how to enforce this at compile time?

Thanks for any help!

like image 590
Tony Eichelberger Avatar asked Dec 18 '08 17:12

Tony Eichelberger


1 Answers

You could emit an error in an annotation processor (you'll have to use a private API if you want Java 5 support). You can use the Messager you get from the ProcessorEnvironment passed to init.

How effective this is might depend on your tool chain. It should be fine if you use javac to compile by the command line or via a build script. In my version of Eclipse, I had to enable annotation processors manually for the project (via project settings) and errors didn't appear anywhere obvious. (The JDT annotation plugins do have extension points that allow better integration with the IDE if you want to provide custom support.) It would pay to check with commonly used tools, especially if you need to support arbitrary development environments.

like image 109
McDowell Avatar answered Oct 20 '22 18:10

McDowell