2

If i were to write my own custom annotation (e.g @Test1, @Test2) and use in the following codes below

public class test {

    @Test1("xxxx")
    @Test2("xxxx")
    public static void main(String[] args){
        System.out.println("Args");
    }
}

And i will like to ensure that if @Test1 is implemented , @Test2 annotation cannot be used as above.

If thats the case, how can i write a validator/parser that can process the source codes to ensure these 2 annotations are not written together?

for example, when compiling it will return a error message indicating this error

2
  • not sure i get it... you want the two to be mutually exclusive?
    – Daij-Djan
    Jun 9, 2013 at 10:54
  • Thanks for your help but i got my answer :D Jun 29, 2013 at 21:02

2 Answers 2

1

Java has an API for this stuff:

JSR-269: „Pluggable Annotation Processing API“, 2006

Google for these terms or for "APT".

Basically this defines an API for compiler-plugins. These plugins can be configured to run within the normal build process and within Eclipse also.

These plugins can do funny things - evaluate annotations, write new source or binary files for example. In your case you just have to emit some error messages (also provided by the API).

Since these plugins are evaluated at compile time, the annotations are not required to have @Retention(CLASS) or @Retention(RUNTIME), SOURCE will be OK. Whether or not this is important for your usecase - I don't know.

But be warned - the internal typesystem is .... interesting (at best).

0
1

This can not be done easily at compile time without a separate tool, such as Maven, but is easy enough to verify at runtime with standard Java.

For a runtime solution, You need to get all of the methods from your class, then iterate over them checking for your annotations. If it has both, then throw an error. .

private static void validateMethodAnnotations(Class<?> myClass){

    for (Method method : myClass.getMethods()){
        Test1 test1 = method.getAnnotation(Test1.class);
        Test2 test2 = method.getAnnotation(Test2.class);
        if (test1 != null && test2 != null){ 
            // both annotations
        }
    }
}
2
  • Although you might be able to roll this into a Maven/Gradle/etc validation plugin and get an error message during packaging..
    – seanhodges
    Jun 7, 2013 at 16:13
  • True, I know there are outside tools to do this. I was just giving a pure standard java solution (caveat that it works at runtime) Jun 7, 2013 at 16:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.