Java注解笔记

不详细说明,个人学习的笔记
只列出代码 和 注释


自定义注解

package top.demo.test;

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;

//@Target
//@Retention
//@Documented
//@Inherited

//规定该注解在什么地方能用
@Target(value= {ElementType.METHOD,ElementType.TYPE})
//规定注解在什么时候能用  runtime 是在程序运行期间都能用,通过反射可得到信息
@Retention(value=RetentionPolicy.RUNTIME)
public @interface MyAnnotation {

    //注解在大括弧里 不是函数代码 实际上上注解的参数
    //类型 名称 默认值
    String test() default "";
    int age() default 18;
    int id();
    String[] arry() default {"1","2"};
    String[] arry2();


}

定义测试类

package top.demo.test;

@MyAnnotation(id=88,arry2= {"99"})
public class Test {

    @MyAnnotation(id=999,arry2= {"888"})
    public static void test1()
    {
        System.out.println("this is annotation test");
    }

}

定义 注解处理类

    package top.demo.test;

    import java.lang.reflect.*;
    import java.lang.annotation.Annotation;

    public class Action {

        public static void main(String argv[]) throws ClassNotFoundException, NoSuchMethodException, SecurityException {

            Class cl=Class.forName("top.demo.test.Test");

            MyAnnotation an=(MyAnnotation) cl.getAnnotation(MyAnnotation.class);
            System.out.println(an.id());

            Method test1=cl.getMethod("test1", null);

            an=test1.getAnnotation(MyAnnotation.class);
            System.out.println(an.id());


        }

    }

猜你喜欢

转载自blog.csdn.net/qq_27617675/article/details/82533766
今日推荐