javaSE注解和反射之获取注解信息

package 反射;

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

public class 获取注解信息 {
    
    

    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
    
    
//        Class c1 = Class.forName("反射.获取注解信息.Student2");

        Student2 student2 = new Student2();

        Class c1 = student2.getClass();
        //通过反射获得注解
        System.out.println(c1);
        Annotation[] annotations = c1.getAnnotations();

        for (Annotation annotation : annotations) {
    
    
            System.out.println(annotation);
        }
        //获得注解value的值
        MyAnnotation1 myAnnotation1 = (MyAnnotation1) c1.getAnnotation(MyAnnotation1.class);
        String value = myAnnotation1.value();
        System.out.println(value);

        //获得指定类的注解

        Field id = c1.getDeclaredField("id");


        System.out.println(id);
        MyAnnotation2 annotation = id.getAnnotation(MyAnnotation2.class);

        System.out.println(annotation.columnName());
        System.out.println(annotation.type());
        System.out.println(annotation.length());
    }

@MyAnnotation1("db_student")
static
class Student2{
    
    

    @MyAnnotation2(columnName = "db_age",type = "int",length = 10)


    private int id;
    @MyAnnotation2(columnName = "db_age",type="int",length = 10)
    private int age;

    @MyAnnotation2(columnName = "db_name",type="String",length = 3)
    private String name;

    public Student2() {
    
    
    }

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

    public int getId() {
    
    
        return id;
    }

    public void setId(int id) {
    
    
        this.id = id;
    }

    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;
    }
}


//类名的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation1{
    
    

    //设置默认参数,默认为value
    String value() default "";
}

//属性的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2{
    
    

    String columnName();
    String type();
    int length();
}

}

猜你喜欢

转载自blog.csdn.net/qq_42794826/article/details/109081052