自定义注解

想深入学习注解,首先要自己定义一个注解。
上一遍写过四种元注解,在自定义注解时会用到。
在自定义注解时需要继承java.lang.annotation.Annotation接口,而用
@interface即会自动继承Annotation接口了,而且自定义注解不能继承其他的注解或接口。
定义注解的方法必须声明为无参数、无异常抛出的。其实每一个方法实际上是声明了一个配置参数,方法的名称就是参数的名称,返回值类型就是参数的类型,其返回值类型有限制的。可以通过default来声明参数的默认值。

定义注解格式:
public @interface 注解名 {定义体}

自定义注解所有可用返回值类型:
1. 所有基本数据类型(int,float,boolean,byte,double,char,long,short)
2. String类型
3. Class类型
4. Enum类型
5. Annotation类型
6. 以上所有类型的数组

 **自定义注解实例:**
/**
 * 类信息注解
 **/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface ClassInfo {
    String author() default "小明";
    String date();
    int version() default 1;
    String description();
}
/**
 * 方法信息注解
 **/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface MethodInfo {
    String author() default "小明";
    String date();
    String description();
}

注解使用

/**
 * Created by cuizhixiang on 2017/6/1.
 * 注解使用
 **/
@ClassInfo(author="小华",date="07-6-17",version=1,description="注解测试类")
public class AnnotionManager {
    @MethodInfo(author="小明",date="01-6-17",description="注解测试方法")
    public void method(){
    }
}

反射解析注解

/**
 * 解析ClassInfo 
 */
private static void analysisClass(){
    Class classes = AnnotionManager.class;
    Annotation annotation = classes.getAnnotation(ClassInfo.class);
    System.out.println(annotation);
}
/**
 * 解析MethodInfo 
 */
private static void analysisMethod(){
    Class classes = AnnotionManager.class;
    Method[] method = classes.getMethods();
    for(Method method1:method){
        MethodInfo methodInfo = method1.getAnnotation(MethodInfo.class);
        if(methodInfo != null){
            System.out.println(methodInfo);
        }
    }
}

运行结果
这里写图片描述

源码已上传:
https://github.com/wolf521/demo/tree/master/src/main/java/com/example/demo/annotation

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值