反射获取注解信息
package com.sinosoft;
import java.lang.annotation.*;
import java.lang.reflect.Field;
public class Test02 {
public static void main(String[] args) throws ClassNotFoundException,NoSuchFieldException{
Class c1 = Class.forName("com.sinosoft.Student");
//通过反射获得注解
Annotation[] annotations = c1.getAnnotations();
for (Annotation annotation: annotations) {
System.out.println(annotation);
}
//获得注解的value值 注解的名字
TableName tableName =(TableName) c1.getAnnotation(TableName.class);
String value = tableName.value();
System.out.println(value);
//获取属性注解的value值
Field name = c1.getDeclaredField("name");
FieldName fieldName = (FieldName)name.getAnnotation(FieldName.class);
String fname = fieldName.columnName();
int length = fieldName.length();
String type = fieldName.type();
System.out.println("name:"+fname+"\nlength:"+length+"\ntype:"+type);
}
}
@TableName(value = "db_student")
class Student {
@FieldName(columnName = "db_name",type="int",length = 30)
private String name;
@FieldName(columnName = "db_age",type="int",length = 10)
private int age;
@FieldName(columnName = "db_id",type="int",length = 10)
private int id;
public Student() {
}
public Student(String name, int age, int id) {
this.name = name;
this.age = age;
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;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", id=" + id +
'}';
}
}
//类名的注解
@Target(ElementType.TYPE)//表示这个注解只能作用在类上
@Retention(RetentionPolicy.RUNTIME)//表示作用在运行时
@interface TableName {
String value();
}
//属性的注解
@Target(ElementType.FIELD)//表示这个注解只能作用在属性上
@Retention(RetentionPolicy.RUNTIME)//表示作用在运行时
@interface FieldName{
String columnName();
String type();
int length();
}
运行结果:
@com.sinosoft.TableName(value=db_student)
db_student
name:db_name
length:30
type:int