java--注解

通常用于项目中的配置,项目中一些不常变的量,比如说域名等,还可以用于装饰者模式

eg:自定义注解
        //在定义注解的时候,需要通过元注解Retention说明当前自定义注解的作用域(Class,  Source,  Runtime)
        @Retention(RetentionPolicy.RUNTIME)
        //自定义注解的时候需要使用Target说明当前的自定义注解的作用范围 
        @Target(ElementType.METHOD)
        public @interface MyAnnotation {
            public long timeout() default -1;
            
            // 不支持自定义类型
            //public MyAnn01 aa();
            
            public Class c() default java.util.Date.class;
        }

    
    //自定义注解的使用  
        public class TestUserAnnotation {
            
            static{
                System.out.println("加载静态代码段");
            }
            @MyAnnotation(timeout = 100)
            public void test01(){
                System.out.println("test01");
            }
            @MyAnnotation(timeout = 100)
            public void test02(){
                System.out.println("test02");
            }
            @MyAnnotation(timeout = 100)
            public void test03(){
                System.out.println("test03");
            }
            @MyAnnotation(timeout = 100)
            public void test04(){
                System.out.println("test04");
            }
            public void test05(){}
            
        }


    //调用使用了自定义注解的类
    public class MyJunit 
    {
        private static Method[] methods;

        public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
        {
            // 加载TestUserAnnotation.class 字节码文件中的方法,判断哪些方法上有自定义的注解,如果有,就执行这个方法
            
            //1_将TestUserAnnotation.class 字节码加载到内存,class对象(代表字节码对象在内存中的对象)
            Class clazz = Class.forName("com.zhujie.TestUserAnnotation");
            //2_获取字节码对象上所有的方法,放回Methods数组对象,数组中每一个元素都代表Method对象(相当于字节码中的一个方法)
            methods = clazz.getMethods();
            //3_遍历方法
            for(Method md:methods)
            {
                //测试方法的名称
                //System.out.println(md.getName());
                //判断当前方法上是否有@MyAnnotation 注解信息
                //System.out.println(md.isAnnotationPresent(MyAnnotation.class));
                //有就执行,否则忽略
                if(md.isAnnotationPresent(MyAnnotation.class))
                {
                    md.invoke(new TestUserAnnotation());
                }
            }
        }
    }

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程

3692 0元 限免
4016 9.8元 98元 1折