美文网首页
Java自定义annotation

Java自定义annotation

作者: 0bbe943b8a86 | 来源:发表于2018-10-19 00:25 被阅读0次

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() {
    ...
}

相关文章

网友评论

      本文标题:Java自定义annotation

      本文链接:https://www.haomeiwen.com/subject/aiuezftx.html