相关概念:
定义注解
package cn.baokx.annotation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target(value={ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)public @interface MyTableAnnotation { String value();}
package cn.baokx.annotation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target(value={ElementType.FIELD})@Retention(RetentionPolicy.RUNTIME)public @interface MyFieldAnnotation { String columnName(); String type();}
package cn.baokx.annotation;@MyTableAnnotation("TBL_STUDENT")public class Student { @MyFieldAnnotation(columnName="NAME",type="VARCHAR") private String name; @MyFieldAnnotation(columnName="AGE",type="INT") private int age; 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; } }
package cn.baokx.annotation;import java.lang.reflect.Field;public class Main { public static void main(String[] args) throws NoSuchFieldException, SecurityException, ClassNotFoundException { Student stu = new Student(); stu.setName("baokx"); stu.setAge(30); handler(stu); } public static void handler(Student stu) throws NoSuchFieldException, SecurityException, ClassNotFoundException{ Class clazz = stu.getClass(); MyTableAnnotation mta = (MyTableAnnotation) clazz.getAnnotation(MyTableAnnotation.class); System.out.println("tableName:"+mta.value()); Field f = clazz.getDeclaredField("name"); MyFieldAnnotation mfa = f.getAnnotation(MyFieldAnnotation.class); System.out.println("columnName:"+mfa.columnName()); System.out.println("type:"+mfa.type()); System.out.println("value:"+stu.getName()); f = clazz.getDeclaredField("age"); mfa = f.getAnnotation(MyFieldAnnotation.class); System.out.println("columnName:"+mfa.columnName()); System.out.println("type:"+mfa.type()); System.out.println("value:"+stu.getAge()); }}