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

后端 未结 2 578
忘了有多久
忘了有多久 2021-02-09 12:32

I have written a java annotation that looks like this:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)  // can I further limit this to only fields         


        
相关标签:
2条回答
  • 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.

    0 讨论(0)
  • 2021-02-09 12:57

    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.

    0 讨论(0)
提交回复
热议问题