Is there any way to let this annotation auto-check

2019-08-23 06:27发布

问题:

@interface Annotation in java.

If I add @Target(value=ElementType.METHOD),this annotation can be import for Java Method.

Is there any way to let this annotation auto-check the Java Method arguments type?

Something like, I have a method:

    @Annotation(type=Integer)
    sayHello(String name)

Once I add the customer Annotation, it will auto check the sayHello argument type is match or not,if it is not match,it will cause the compile error.

Is it can be implemented? If, how? Exclude the thought using java Reflect in Runtime to check,this will not fit my idea.

Thanks in advance.

回答1:

You need to (1) make your own annotation processor whose API is provided by javax.annotation.processing and javax.lang.model packages of JDK which will be invoked during compilation and make necessary checks. (2) attach it using SPI

(1) For example, given the annotation

package aptest;    
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.SOURCE)
public @interface Annotation {
    Class<?> type();
}

the annotation processor might look like this:

package aptest;
// ... imports
@SupportedAnnotationTypes({"aptest.Annotation"})
public class AnnotationProcessor extends AbstractProcessor 
    implements Processor {

    @Override
    public boolean process(Set<? extends TypeElement> annotations,
            RoundEnvironment roundEnv) {        
        for (TypeElement te : annotations) {
              for (Element e : roundEnv.getElementsAnnotatedWith(te)) {
                  // do your checking
              }
        }
        return true;
    }

}

(2) When you package your annotation processor (let's say in aptest.jar) you include META-INF/services/javax.annotation.processing.Processor file containing the name of you annotation processor class:

aptest.AnnotationProcessor

And when you compile your code the annotation processor will be invoked. To use it, the command line should like like this:

javac -cp aptest.jar SayHello.java