强制具有特定注释的方法具有特定参数/签名 [英] Compell a method with specific annotation to have specific parameters/signature

查看:36
本文介绍了强制具有特定注释的方法具有特定参数/签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个注释:

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();
}

我有两个类:

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;
}

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

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?

推荐答案

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

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

我建议:

  • 考虑将 AbstractProcessor 作为基类
  • 考虑使用 javax.annotation.processing
  • 将处理器注册为服务在 META-INF/服务中
  • 将注释处理器和注释打包在同一个 jar 中 - 连同注册为服务,这将在使用自定义注释处理器时启用处理器
  • 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

这篇关于强制具有特定注释的方法具有特定参数/签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆