栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

反射操作注解

java的注解原理

package cn.usts.edu.ReflectionGetAndSetAnnotation;


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


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();
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/356643.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号