Compell a method with specific annotation to have specific parameters/signature

时光总嘲笑我的痴心妄想 提交于 2020-01-30 05:06:30

问题


I have an annotation as:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    String annotationArgument1() default "";
    String annotationArgument2();
}

I have two classes as:

class MyClass1 {
    @MyAnnotation(annotationArgument1="ABC", annotationArgument2="XYZ")
    public void method1(MyClass2 object) {
        //do something
    }

    @MyAnnotation(annotationArgument1="MNO", annotationArgument2="PQR")
    public void method2(MyClass2 object) {
        //do something
    }
}

class MyClass2 {
    int num;
}

I want method1 and method2 (or any other method in any other class annotated with @MyAnnotation) to take only one argument as MyClass2 because they are annotated with @MyAnnotation. If some other argument is passed, it must give a compile time error.

Is it actually possible to do this? If yes, how can it be done and if no, what is alternate to make this kind of behavior possible?


回答1:


AFAIK, you can use an annotation processor to check the method signature at compile-time.

I recommend to:

  • consider AbstractProcessor as a base class
  • consider to use the annotations provide by the javax.annotation.processing package
  • register the Processor as a service in META-INF/services
  • package the annotation processor and the annotations in the same jar - together with the registration as a service this will enable the processor whenever your custom annotation processor is used


来源:https://stackoverflow.com/questions/30798279/compell-a-method-with-specific-annotation-to-have-specific-parameters-signature

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!