package com.company;
import java.lang.annotation.*;
import java.lang.reflect.Field;
public class test3 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class c1 = Class.forName("com.company.Student2");
//通过反射获得注解
Annotation[] annotations = c1.getAnnotations();
for (Annotation annotation:annotations){
System.out.println(annotation);
}
//获得注解的value的植
annon annotations1 = (annon) c1.getAnnotation(annon.class);
String value = annotations1.value();
System.out.println(value);
//获得id类指定的注解
Field id = c1.getDeclaredField("id");
bnnon annotation = id.getAnnotation(bnnon.class);
System.out.println(annotation.columnName());
System.out.println(annotation.type());
System.out.println(annotation.length());
Field age = c1.getDeclaredField("age");
bnnon annotationage = age.getAnnotation(bnnon.class);
System.out.println(annotationage.columnName());
System.out.println(annotationage.type());
System.out.println(annotationage.length());
Field name = c1.getDeclaredField("age");
bnnon annotationagename = name.getAnnotation(bnnon.class);
System.out.println(annotationagename.columnName());
System.out.println(annotationagename.type());
System.out.println(annotationagename.length());
}
}
@annon("biaoming")
class Student2{
@bnnon(columnName = "db_id",type = "int",length = "1")
private int id;
@bnnon(columnName = "db_age",type = "int",length = "3")
private int age;
@bnnon(columnName = "db_name",type = "String",length = "4")
private String name;
public Student2(int id, int age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
public Student2() {
}
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 "Student2{" +
"id=" + id +
", age=" + age +
", name='" + name + '\'' +
'}';
}
}
@Target({ ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface annon{
String value();
}
@Target({ ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@interface bnnon{
String columnName();
String type();
String length();
}
还没有评论,来说两句吧...