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

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

问题描述

我的注释为:

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 视为基类
  • 考虑使用服务在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天全站免登陆