一: 定义注解实体
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 类描述:分页注解
* @version 1.0 CreateDate: 2015-2-10
*
* @history:
* @updateDate @updatePerson @declare
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER,ElementType.TYPE,ElementType.METHOD,ElementType.FIELD})
public @interface PagerAnno {
String value();
}
1:元注解是指注解的注解。包括 @Retention @Target @Document @Inherited四种
2:元注解之 @Retention (保留)
@Retention(RetentionPolicy.SOURCE) //注解仅存在于源码中,在class字节码文件中不包含
package commons.anno;
import org.apache.ibatis.annotations.Param;
/**
* 类描述: 注解寄主
* @version 1.0 CreateDate: 2015-2-11
*
* @history:
* @updateDate @updatePerson @declare
*
*/
@PagerAnno("注释到类ApplTest")
public class ApplTest {
@PagerAnno("注释到类成员变量.....")
private String name;
@PagerAnno("注释到方法sysHi")
public void sysHi(){
System.out.println("hi......");
}
@PagerAnno("注释到方法sysHello")
public void sysHello(@Param("mybatis 注解--> @param")@PagerAnno("注释到方法参数String name")String name){
System.out.println("hello");
}
}
三:获取注解
package commons.anno;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.apache.ibatis.annotations.Param;
/**
* 类描述: 注解测试入口
* @version 1.0 CreateDate: 2015-2-11
*
* @history:
* @updateDate @updatePerson @declare
*
*/
public class Acce {
public static void main(String[] args) {
//打印类上的注解
Annotation[] annoArry = ApplTest.class.getAnnotations();
for(Annotation anno : annoArry){
if(anno instanceof PagerAnno){
System.out.println(((PagerAnno)anno).value());
}
}
Method[] methodArry = ApplTest.class.getMethods();
for(Method method : methodArry){
//打印方法上的注解
for(Annotation anno : method.getAnnotations()){
if(anno instanceof PagerAnno){
System.out.println(((PagerAnno)anno).value());
}
}
//打印方法形参上的注解
for(Annotation[] annos : method.getParameterAnnotations()){
for(Annotation anno : annos){
if(anno instanceof PagerAnno){
System.out.println(((PagerAnno)anno).value());
}else if(anno instanceof Param){
System.out.println(((Param)anno).value());
}
}
}
}
//打印成员变量上的注解
Field[] fieldArry = ApplTest.class.getDeclaredFields();
for(Field field : fieldArry){
for(Annotation anno : field.getAnnotations()){
if(anno instanceof PagerAnno){
System.out.println(((PagerAnno)anno).value());
}
}
}
}
}
原文:http://www.cnblogs.com/leonkobe/p/4285931.html