自定义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)
原文地址:https://www.cnblogs.com/sunzhongyu008/p/11226332.html