Java反射读取注解时有时无的情况

tb_bin 2018-01-12 03:57:33
java反射中,method.getParameterAnnotations 有时候可以正常读取到注解数组, 但是多数情况读取不到注解数组是什么情况 ? 有入坑的伙伴没 ? 

public class MethodDemo {
public static void main(String[] args){
Method[] methods = SampleClass.class.getMethods();
Annotation[][] annotations = methods[1].getParameterAnnotations();
for (Annotation[] annotation1 : annotations) {
for (Annotation annotation : annotation1) {
if (annotation instanceof CustomAnnotation) {
CustomAnnotation customAnnotation = (CustomAnnotation) annotation;
System.out.println("name: " + customAnnotation.name());
System.out.println("value: " + customAnnotation.value());
}
}
}
}
}

@CustomAnnotation(name = "SampleClass", value = "Sample Class Annotation")
class SampleClass {
private String sampleField;

public String getSampleField() {
return sampleField;
}

public void setSampleField(
@CustomAnnotation(name = "sampleClassMethod", value = "Sample Method Annotation") String sampleField) {
this.sampleField = sampleField;
}
}

@Retention(RetentionPolicy.RUNTIME)
@interface CustomAnnotation {
public String name();

public String value();
}

比如上述代码,有时候可以正常打印出结果:
  name: sampleClassMethod
  value: Sample Method Annotation
有时候就读取不到 . 
...全文
225 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
maradona1984 2018-01-12
  • 打赏
  • 举报
回复
或许你该打印下methods[1]到底是哪个方法
tb_bin 2018-01-12
  • 打赏
  • 举报
回复
没人入坑吗 ? 

50,530

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧