强制具有特定注释的方法具有特定参数/签名

Muk*_*lan 6 java annotations

我有一个注释:

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();
}
Run Code Online (Sandbox Code Playgroud)

我有两个类:

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;
}
Run Code Online (Sandbox Code Playgroud)

我希望method1method2(或任何其他类中用 注释的任何其他方法@MyAnnotation)只接受一个参数,MyClass2因为它们用@MyAnnotation. 如果传递了其他参数,则必须给出编译时错误。

实际上有可能做到这一点吗?如果是,怎么做,如果不是,有什么办法可以使这种行为成为可能?

Puc*_*uce 4

AFAIK,您可以使用注释处理器在编译时检查方法签名。

我建议:

  • AbstractProcessor视为基类
  • 考虑使用javax.annotation.processing包提供的注释
  • 将处理器注册为META-INF/services 中的服务
  • 将注释处理器和注释打包在同一个 jar 中 - 连同注册为服务,这将在使用自定义注释处理器时启用处理器