关于使用反射无法取得部分注解

要设置@Retention(RetentionPolicy.RUNTIME)这个表示运行期注解,这样在反射的时候才能取到
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要给某个方法添加注解,可以使用反射来实现。下面是一个示例代码: ```java import java.lang.annotation.Annotation; import java.lang.reflect.Method; public class AnnotationExample { public static void main(String[] args) throws NoSuchMethodException { // 获取要添加注解的方法 Method method = MyClass.class.getMethod("myMethod"); // 获取注解类的实例 MyAnnotation annotation = method.getAnnotation(MyAnnotation.class); // 如果方法已经有注解,则输出注解的值 if (annotation != null) { System.out.println("MyAnnotation value: " + annotation.value()); } // 动态添加注解 if (annotation == null) { // 获取注解类 Class<MyAnnotation> annotationClass = MyAnnotation.class; // 创建一个注解实例 MyAnnotation newAnnotation = annotationClass.newInstance(); // 设置注解的值 newAnnotation.setValue("New Value"); // 获取方法的注解数组 Annotation[] annotations = method.getDeclaredAnnotations(); // 创建一个新的注解数组,长度比原数组多1 Annotation[] newAnnotations = new Annotation[annotations.length + 1]; // 将原数组的元素复制到新数组中 System.arraycopy(annotations, 0, newAnnotations, 0, annotations.length); // 将新注解添加到新数组的最后一个位置 newAnnotations[newAnnotations.length - 1] = newAnnotation; // 使用反射设置方法的注解数组 Method annotationsMethod = Method.class.getDeclaredMethod("declaredAnnotations"); annotationsMethod.setAccessible(true); annotationsMethod.invoke(method)[0] = newAnnotations; } } } // 自定义注解 @interface MyAnnotation { String value() default ""; } // 被注解的类 class MyClass { @MyAnnotation("Old Value") public void myMethod() { System.out.println("MyMethod"); } } ``` 上述代码中,首先通过反射获取要添加注解的方法。然后,判断方法是否已经有注解,如果有则输出注解的值。如果方法没有注解,则使用反射动态添加注解。具体实现是通过创建一个新的注解实例,并设置注解的值,然后将新注解添加到方法的注解数组中。最后使用反射设置方法的注解数组。这样就成功给方法添加了注解

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值