首页 > 其他分享 >获取注解信息

获取注解信息

时间:2023-03-27 14:44:18浏览次数:27  
标签:String int age 信息 public 获取 注解 id name

package edu.wtbu;

import java.lang.annotation.*;

//练习反射操作注解
public class Demo01 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class<?> c1 = Class.forName("edu.wtbu.Student1");
//通过反射获得注解
Annotation[] annotations = c1.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);//@edu.wtbu.Table("dh_Student")
}

//获得注解的value的值
Table table = (Table) c1.getAnnotation(Table.class);
String value = table.value();
System.out.println(value);//dh_Student

//获得类指定的注解
java.lang.reflect.Field name = c1.getDeclaredField("name");
Field annotation = name.getAnnotation(Field.class);
System.out.println(annotation.columnName());//db_name
System.out.println(annotation.type());//String
System.out.println(annotation.length());//3
}

}

@Table("db_Student")
class Student1{
@Field(columnName = "db_id",type = "int",length = 10)
private int id;
@Field(columnName = "db_age",type = "int",length = 10)
private int age;
@Field(columnName = "db_name",type = "String",length = 3)
private String name;

public Student1() {

}

public Student1(int id, int age, String name) {
this.id = id;
this.age = age;
this.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;
}

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

//类名的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Table{
String value();
}

//属性的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Field{
String columnName();
String type();
int length();
}

标签:String,int,age,信息,public,获取,注解,id,name
From: https://www.cnblogs.com/123456dh/p/17261491.html

相关文章