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)
  • 相关阅读:
    浅谈求卡特兰数的几种方法
    WPF基础知识、界面布局及控件Binding
    .net平台下C#socket通信(上)
    .net泛型理解
    面向过程和面向对象及面向对象的三大特征
    C#配置文件管理
    MOGRE学习笔记(3)--MOGRE小项目练习
    委托、事件学习笔记
    MOGRE学习笔记(2)
    MOGRE学习笔记(1)
  • 原文地址:https://www.cnblogs.com/sunzhongyu008/p/11226332.html
Copyright © 2011-2022 走看看