java注解和反射--通过反射获取到注解的值

反射操作注解

java的注解原理
在这里插入图片描述

package cn.usts.edu.ReflectionGetAndSetAnnotation;


import java.lang.annotation.*;
import java.lang.reflect.Field;

/**
 * @author :fly
 * @description: 利用反射操作注解
 * @date :2021/10/29 15:36
 */
public class GetSetAnnotation {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
        // 通过反射获取对象
        Class<?> u1 = Class.forName("cn.usts.edu.ReflectionGetAndSetAnnotation.User");

        // 通过反射对象获取注解
        Annotation[] annotations = u1.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }

        //   获取注解对象                                         注解名子.class
        testAnnotation1 testAnnotation1 =u1.getAnnotation(testAnnotation1.class);
        // 获取注解的value         注解对象.属性()
        System.out.println(testAnnotation1.tableName());

        // 获取指定属性
        Field age = u1.getDeclaredField("age");
        // 指定属性上的注解
        testFiledAnnotation ageAnnotation = age.getAnnotation(testFiledAnnotation.class);
        System.out.println("columnName-->"+ageAnnotation.columnName());
        System.out.println("type-->"+ageAnnotation.type());
        System.out.println("length-->"+ageAnnotation.length());
    }


}

@testAnnotation1(tableName = "tb_User")
class User{
    @testFiledAnnotation(columnName = "User_age",type = "int",length = 10)
    int age;
    @testFiledAnnotation(columnName = "User_name",type = "varChar",length = 20)
    String name;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public User() {
    }

    public User(int age, String name) {
        this.age = age;
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

// 类注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface testAnnotation1{
    String tableName();
}

// 属性注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface testFiledAnnotation{
    String columnName();
    int length();
    String type();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值