Java自定义annotation

annotation里面的method只能返回原始数据类型(byte, char, int, long, double, float, boolean, void)或者String, Class, enum, 或者 Array(里面必须是上述的类型).

annotation的method不能传参数

在Java里可以自己定义annotation
需要使用@interface来定义
有三种annotations

第一种 marker annotation

@interface SampleMarkerAnnotation {}

没有方法在里面

第二种 single value annotation

@interface SampleSingleValueAnnotation {
    int method1();
}

也可以有default值

@interface SampleSingleValueAnnotation {
    int method1() default 0;
}

@SampleSingleValueAnnotation(method1=10)
public class SampleClass() {
    ...
}

第三种 multi-value annotation

@interface SampleMultiValueAnnotation {
    int method1();
    String method2();
    void method3();
}

也可以有default值

@interface SampleMultiValueAnnotation {
    int method1() default 0;
    String method2() default "Hello";
    void method3();
}

@ SampleMultiValueAnnotation(method1=10, method2="NiHao")
public class SampleClass() {
    ...
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容