views:

193

answers:

2

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!

A: 

I believe that this is not enforcable at compile-time - If you want to ensure that it is not on any inappropriate fields, you would have to check at run/load-time.

Nathaniel Flath
+5  A: 

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.

McDowell
That is the information I was looking for. I will dig in and see if it is worthwhile adding these checks. Thanks.
Tony Eichelberger