Java自定义annotation

2018-10-19  本文已影响0人  0bbe943b8a86

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() {
    ...
}
上一篇 下一篇

猜你喜欢

热点阅读