Java———Annotation自定义注解(二)*

来源:互联网 发布:ubuntu 安装无线网卡 编辑:程序博客网 时间:2024/06/07 00:46

自定义一个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.METHOD })public @interface MyAnnotation {    /**     * 姓名     *      * @return     */    String name() default "张三";    /**     * 年龄     *      * @return     */    int age();    /**     * 爱好     *      * @return     */    String[] hobby() default { "打篮球", "踢足球" };}

获取Annotation内的信息

import java.lang.annotation.Annotation;public class A {    public static void main(String[] args) throws SecurityException,            NoSuchMethodException, ClassNotFoundException {        // 第一步:拿到指定位置的注解        Annotation[] arr = null;        arr = Class.forName("B").getMethod("man").getAnnotations();        // 第二步:拿到位置中的具体什么注解        for (Annotation a : arr) {            System.out.println(a);            // 第三步:取出注解内容            if (a instanceof MyAnnotation) {                System.out.println("姓名:" + ((MyAnnotation) a).name());                System.out.println("年龄:" + ((MyAnnotation) a).age());                for (String str : ((MyAnnotation) a).hobby()) {                    System.out.println("爱好:" + str);                }            }        }    }}class B {    @MyAnnotation(age = 20)    public void man() {    }}
0 0
原创粉丝点击