反射读取注解

java反射读取注解

package Annotation;
@Annotation
public class TestAnnontation {
@Annotation(a = “sa”,b = 4)
public void test() {

}

}
package Annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.FIELD})
public @interface Annotation1_2 {
String columnname();
String type();
String length();
}
package Annotation;

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

@Annotation1_1(name = “mzt_student”)
public class TestAnnotation1 {
@Annotation1_2(columnname = “id”,type = “int”,length = “10”)
private int id;
@Annotation1_2(columnname = “studentname”,type = “varchar”,length = “10”)
private String studentname;
@Annotation1_2(columnname = “age”,type = “int”,length = “10”)
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStudentname() {
return studentname;
}
public void setStudentname(String studentname) {
this.studentname = studentname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}

	public static void  main(String args[]) throws Exception {
    	Class c = Class.forName("Annotation.TestAnnotation1");
    	//获取所有有效注解
    	Annotation[] a = c.getAnnotations();
    	for(Annotation a1:a) {
    		System.out.println(a1);
    	}
    	//获取类的指定注解
    	 Annotation1_1  a2 = (Annotation1_1) c.getAnnotation( Annotation1_1.class);
    	 System.out.println(a2.name());
    	 //获取类的属性注解
    	 Field f =  c.getDeclaredField("id");
    	 Annotation1_2 a3 = f.getAnnotation(Annotation1_2.class);
    	 System.out.println(a3.columnname()+a3.type()+a3.length());
     }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值