反射注解基本操作

注解和反射

1.注解-annotation

1.1 元注解

元注解的作用就是负责注解其他注解(@Target、@Retention、@Documented、@Inherited)

@Target:描述注解的使用范围(方法、类、参数上等)——多个使用范围,必须加上{ }

@Retention: 定义了注解保持有效的 使命周期阶段(runtime(默认写这个) >class>sources)

@Documented: 表示是否将我们的注解生成在JavaDoc中

@Inherited: 子类可以继承父类的注解

//@Retention 定义了注解保持有效的 使命周期阶段
@Retention(RetentionPolicy.RUNTIME)
//@Target 表示注解能使用的目标
@Target({
   ElementType.TYPE,ElementType.METHOD,ElementType.PARAMETER})
//@Documented:表示是否将我们的注解生成在JavaDoc中
@Documented
//@Inherited:子类可以继承父类的注解
@Inherited
public @interface MyAnnotation {
   
    //成员
    String userName() default "张三";  

    int age();

    boolean flag() default true;

    //枚举
    Color color() default Color.RED;

    //注解
    OtherAnnotation othanno();
}

注意:

  1. 注解:主要作用就在程序中传值(在运行阶段完成:结合反射使用)

  2. 在注解中参数可以用default来定义默认值

  3. 调用自定义自定义注解,注解有一个成员参数可以直接写参数值,注解有多个成员参数,必须用参数名value= ;

  4. 注解中有默认值,可以不用给其赋值·

  5. 注解中的成员参数是数组且数组只有一个元素时,{}可以省略,否则{}不能省略

    @MyAnnotation(userName = "李四",age = 16,color = Color.RED,othanno = @OtherAnnotation(1))
    public class annotationDemo {
         
        public static void main(String[] args) {
         
            System.out.println("   ");
        }
    }
    
1.2 通过基本反射读取注解

annotationDemo类:设置注解

@MyAnnotation(userName = "王啊五",age = 4,flag = true,color = Color.RED,othanno = @OtherAnnotation(1))
public class annotationDemo {
   

    @MyAnnotation(userName = "李四",age = 5,othanno = @OtherAnnotation(4))
    private static void print(@MyAnnotation(age = 1,othanno = @OtherAnnotation(1))String userName,@MyAnnotation(age = 7,userName = "刘六")Integer id){
   
        
        System.out.println("你好");
    }

}

TestGetValue类:分别读取类上、方法上、参数上的注解

public class TestGetValue {
   
    public static void main(String[] args) throws NoSuchMethodException {
   
        Class<TestAnnotation> annotationClass = TestAnnotation.class;

        //获取方法参数中的注解
        Method print = annotationClass.getDeclaredMethod("print", String.class, Integer.class);
        Parameter[] parameters = print.getParameters();
        for (Parameter parameter : parameters) {
   
            boolean annotationPresent = parameter.isAnnotationPresent(MyAnnotation.class);
            if (annotationPresent) {
   
                MyAnnotation annotation 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值