gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:40:12 27 4
gpt4 key购买 nike

我有一个注释:

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):

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 注释的。如果传递了其他参数,则必须给出编译时错误。

实际上可以做到这一点吗?如果是,如何才能做到?如果不是,有什么替代方法可以使这种行为成为可能?

最佳答案

据我所知,您可以使用 annotation processor在编译时检查方法签名。

我建议:

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

关于java - 强制具有特定注释的方法具有特定参数/签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59947727/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com