Java使用反射获取注解信息的简介说明

本文详细介绍了Java中如何通过反射获取类、方法和参数上的注解信息,包括@MyAnnotation的实例化和属性访问。

转自:

Java使用反射获取注解信息的简介说明

下文笔者讲述使用java反射获取注解信息的方法分享,如下所示:

注解简介说明

注解可以理解为java代码的一个注释,注解本身不起任何作用,它需要借助反射为类做一些扩展功能
例:注解的使用

//TestClass上使用了注解@MyAnnotation
@MyAnnotation(name="java",value="java265.com")
public class TestClass {
}

//定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyAnnotation {
  public String name();
  public String value();
}

java访问注解的示例分享

Class aClass = TestClass.class;
Annotation[] annotations = aClass.getAnnotations();
for(Annotation annotation : annotations){
    if(annotation instanceof MyAnnotation){
        MyAnnotation myAnnotation = (MyAnnotation) annotation;
        System.out.println("name: " + myAnnotation.name());
        System.out.println("value: " + myAnnotation.value());
    }
} 

方法注解

public class TestClass {
  @MyAnnotation(name="methoName",  value = "this is method")
  public void testFun(){}
}
 
Method method = ... //获取方法对象
Annotation[] annotations = method.getDeclaredAnnotations();
for(Annotation annotation : annotations){
    if(annotation instanceof MyAnnotation){
        MyAnnotation myAnnotation = (MyAnnotation) annotation;
        System.out.println("name: " + myAnnotation.name());
        System.out.println("value: " + myAnnotation.value());
    }
}

参数注解

 public class TestClass {
  public static void testFun(
        @MyAnnotation(name="aName", value="aValue") String parameter){
  }
}

//使用Method对象来访问方法参数注解

Method method = ... //获取方法对象
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
Class[] parameterTypes = method.getParameterTypes();
int i=0;
for(Annotation[] annotations : parameterAnnotations){
  Class parameterType = parameterTypes[i++];
  for(Annotation annotation : annotations){
    if(annotation instanceof MyAnnotation){
        MyAnnotation myAnnotation = (MyAnnotation) annotation;
        System.out.println("param: " + parameterType.getName());
        System.out.println("name : " + myAnnotation.name());
        System.out.println("value: " + myAnnotation.value());
    }
  }
}
---------------------
注意事项:
    Method.getParameterAnnotations()方法返回一个注解类型的二维数组

变量注解

public class TestClass {
  @MyAnnotation(name="someName",  value = "Hello World")
  public String myField = null;
}

Field field = ... //获取方法对象
Annotation[] annotations = field.getDeclaredAnnotations();
for(Annotation annotation : annotations){
 if(annotation instanceof MyAnnotation){
 MyAnnotation myAnnotation = (MyAnnotation) annotation;
 System.out.println("name: " + myAnnotation.name());
 System.out.println("value: " + myAnnotation.value());
 }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值