注解与反射

package com.nty.reflection;

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

//练习反射操作注解
public class Test11 {

public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {

    Class c1 = Class.forName("com.nty.reflection.Student2");

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

    //获得注解value的值
    TestAnno testAnno = (TestAnno) c1.getAnnotation(TestAnno.class);
    System.out.println(testAnno.value());//db_student

    System.out.println("================================");
    //获得类指定的注解
    Field f = c1.getDeclaredField("name");
    FieldAnno annotation = f.getAnnotation(FieldAnno.class);
    System.out.println(annotation.columnName());//db_name
    System.out.println(annotation.type());//varchar
    System.out.println(annotation.length());//10
}

}

@TestAnno("db_student")
class Student2 {
@FieldAnno(columnName = "db_id", type = "int", length = 10)
private int id;
@FieldAnno(columnName = "db_name", type = "varchar", length = 10)
private String name;
@FieldAnno(columnName = "db_age", type = "int", length = 10)
private int age;

public Student2() {
}

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

public int getId() {
    return id;
}

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

public String getName() {
    return name;
}

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

public int getAge() {
    return age;
}

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

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

}

//创建一个注解
@Target(ElementType.TYPE)//类上使用
@Retention(RetentionPolicy.RUNTIME)
//Retention:表示我们的注解在什么地方有效
@interface TestAnno {
String value();

}

//属性的注解
@Target(ElementType.FIELD)//类上使用
@Retention(RetentionPolicy.RUNTIME)
@interface FieldAnno {
String columnName();

String type();

int length();

}

posted @ 2022-05-01 17:46  study小凝  阅读(38)  评论(0)    收藏  举报