zoukankan      html  css  js  c++  java
  • 自定义Annotation

    除了使用系统提供的Annotation之外,又留给开发者自定义Annotation的支持,此时就需要明确的指定Annotation的操作范围,本课程主要讲解Annotation的定义,以及结合反射获取信息处理。

    范例1:自定义Annotation

    package com.customAnnotation.demo;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.reflect.Method;
    
    @Retention(RetentionPolicy.RUNTIME)        //定义Annotation运行策略
    @interface DefaultAnnotation{            //自定义的Annotation
        public String title();                //获取数据
        public String url() default "www.mldn.com";        //获取数据,默认值
    }
    class Message{
        @DefaultAnnotation(title = "MLDN")
        public void send(String msg) {
            System.out.println("【消息发送】" + msg);
        }
    }
    
    public class CustomAnnotation{
        public static void main(String[] args) throws Exception{
            Method method = Message.class.getMethod("send", String.class); //获取指定方法
            DefaultAnnotation anno = method.getAnnotation(DefaultAnnotation.class);//获取指定的Annotation
            String msg = anno.title() + "(" + anno.url() + ")";//消息内容
            method.invoke(Message.class.getDeclaredConstructor().newInstance(), msg);
        }
    }

    运行结果:

    【消息发送】MLDN(www.mldn.com)

    范例2:自定义Annotation

    package com.customAnnotation.demo;
    
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    import java.lang.reflect.Method;
    
    @Target({ElementType.TYPE, ElementType.METHOD})// 此Annotation只能用在类和方法上
    @Retention(RetentionPolicy.RUNTIME)//定义Annotation的运行策略
    @interface DefaultAnnotation{//自定义Annotation
        public String title();//获取数据
        public String url() default "www.sohu.com";//获取数据,提供默认值
    }
    class Message{
        @DefaultAnnotation(title = "搜狐")
        public void send(String msg) {
            System.out.println("【消息发送】" + msg);
        }
    }
    public class CustomAnnotation {
        public static void main(String[] args) throws Exception {
            Method method = Message.class.getMethod("send", String.class);
            DefaultAnnotation ca = method.getAnnotation(DefaultAnnotation.class);
            String msg = ca.title() + "(" + ca.url() + ")";
            method.invoke(Message.class.getDeclaredConstructor().newInstance(), msg);
        }
    }

    运行结果:

    【消息发送】搜狐(www.sohu.com)
  • 相关阅读:
    SQL必知必会-笔记(五)函数
    软件测试面试题:系统中的图片不显示如何排查原因
    windows用浏览器访问linux目录文件
    记测试工作中一次印象深刻的事
    怎么快速适应新的测试工作?
    xshell如何导出日志文件和上传文件
    jmeter+fiddler高效率整理接口脚本
    python-用requests库处理form-data格式的参数
    软件自动化测试工程师面试题集锦(4)
    shell脚本批量检查某个或多个服务的端口和进程是否正常
  • 原文地址:https://www.cnblogs.com/sunzhongyu008/p/11226332.html
Copyright © 2011-2022 走看看