A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© scenery_sky 中级黑马   /  2014-6-30 00:28  /  1247 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

1.1 自定义一个类注解

?
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface AkClass {
    String value() default "hello";
}
1.2 类注解的使用,如:

?
import demo.annontation.AkClass;
@AkClass()
public interface AkClassTest {
     
    public abstract void getAK();

}
1.3 通过java反射机制获取和解析类注解,如:

注意:只有当类注解使用了RetentionPolicy.RUNTIME保留策略,才能在运行时,通过java反射机制获取

?
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import demo.annontation.AkClass;
import demo.annontation.AkMethod;

/**
* 掃描當前包裏面,哪些類被AkClass類注解標記過
*
*/

public class Main {
     
    public static void main(String[] args) {
        //判斷某個類是否是注解
        System.out.println("對象是否為注解類型:"+AkClassTest.class.isAnnotation());
        System.out.println("調用類指定的類注解屬性值:"+AkClassTest.class.getAnnotation(AkClass.class).value());
        //獲取某個具體類的所有注解
        Annotation[] annotations = AkClassTest.class.getAnnotations();
        for(Annotation annotation : annotations){
            //判斷當前注解對象是否為自定義注解
            if(annotation.annotationType() == AkClass.class){
                System.out.println("類注解名稱:"+AkClass.class.getSimpleName());
                Method[] methods = AkClass.class.getDeclaredMethods();
                for(Method method : methods){
                    System.out.println("類注解方法:"+method.getName());
                }
                System.out.println();
            }
        }
        System.out.println("獲取某個類中所有方法的所有方法注解");
        Method[] methods = AkClassTest.class.getMethods();
        for(Method method : methods){
            System.out.println("類方法名:"+method.getName());
            System.out.println("調用方法注解的屬值性:"+method.getAnnotation(AkMethod.class).value());
            Annotation[] mAnnotations = method.getAnnotations();
            for(Annotation mAnnotation : mAnnotations){
                if(mAnnotation.annotationType() == AkMethod.class){
                    System.out.println("注解名:"+AkMethod.class.getSimpleName());
                }
            }
        }
    }
}

1 个回复

倒序浏览
今天刚学到
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马