package com.reflection;
import java.lang.annotation.*;
import java.lang.reflect.Field;
public class test08 {
public static void main(String [] args) throws ClassNotFoundException, NoSuchFieldException {
Class c1=Class.forName("com.reflection.test0111");
//这样只能获得类的注解
Annotation[] annotations = c1.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);//输出:@com.reflection.mytypeannotation(value=user_info)
}
//获得类注解的value值
Myclassannotation myclassannotation=(Myclassannotation)c1.getAnnotation(Myclassannotation.class);
String value =myclassannotation.value();
System.out.println(value);//输出user_info
//获得指定属性的注解
Field f= c1.getDeclaredField("name");//先获得指定的属性
MyAnnotation myAnnotation= f.getAnnotation(MyAnnotation.class);//通过属性,获得该注解
System.out.println(myAnnotation.coluname());//获得该注解的columnname属性
System.out.println(myAnnotation.length());//获得该注解的length属性
System.out.println(myAnnotation.type());//获得该注解的type属性
}
}
@Retention(value= RetentionPolicy.RUNTIME )//表示运行时有效
@Target(value = ElementType.FIELD)//表示只能用在变量中
@interface MyAnnotation {
String coluname();
String type();
int length();
}
@Retention(value= RetentionPolicy.RUNTIME )//表示运行时有效
@Target(value = ElementType.TYPE)//表示只能用在方法中
@interface Myclassannotation {
String value();
}
test0111
package com.reflection;
@Myclassannotation("user_info")
class test0111
{
@MyAnnotation(coluname = "user_name",type = "String",length = 10)
private String name;
@MyAnnotation(coluname = "user_id",type = "int",length = 11)
private int age;
@MyAnnotation(coluname = "user_id",type = "int",length = 12)
private int id;
@Override
public String toString() {
return "test01{" +
"name='" + name + '\'' +
", age=" + age +
", id=" + id +
'}';
}
public test0111(String name, int age, int id) {
this.name = name;
this.age = age;
this.id = id;
}
public test0111() {
}
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;
}
}