前段时间用Hibernate时用注解(即annotation)的方式来定义元数据的映射,一直都很想知道annotation是怎么实现的,今天终于做了一个自己的annotation demo
1、定义一个annotation的接口
package annotation.test;
/**
* @author longtop
*
*/
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Description {
String column();
String comment();
}
2、在类中引用annotation
package annotation.test;
public class TableTest {
public String id;
public String name;
@Description(column = "id",comment="主键")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Description(column = "name", comment = "用户名")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
3、一个测试类,取出annotation定义的元数据
package annotation.test;
import java.lang.reflect.Method;
public class Test {
public static void main(String[] args) {
String className = "annotation.test.TableTest";
try {
Class tableTest = Class.forName(className);
Method[] method = tableTest.getMethods();
Description des = null;
for (int i = 0; i < method.length; i++) {
Method meth = method[i];
if (meth.isAnnotationPresent(Description.class)) {
des = meth.getAnnotation(Description.class);
//System.out.println(des.annotationType());
System.out.println(des.column() + " : " + des.comment());
}
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
还有什么高级的应用,请大家不吝赐教阿。