目录
- 一 笔记
- 二 自定义注解类型 @MyAnnotation
- 三 自定义注解类型 @MyAnnotation2
- 四 自定义注解类型 @MyAnnotation3
- 五 自定义注解类型 @MyAnnotation4
- 六 使用自定义的注解类
一 笔记
- 当一个注解定义了属性,那么在使用该注解时必须给该注解的属性赋值;否则会报编译错误;
- 语法格式: @注解名(属性名=属性值,属性名=属性值…) 如 @MyAnnotation(age = 2)
- 定义注解属性时添加了默认值,在使用注解时可以不写该属性 String color() default “red”;
- 注解名为“value”时,使用时可以省略注解名;@MyAnnotation3(value = “zz”) 和 @MyAnnotation3(“zz”) 效果相同
- 数组中如果只有一个元素,使用属性时,{}可以省略;@MyAnnotation4(names = {“jack”}) 和 @MyAnnotation4(names = “jack”)效果相同
二 自定义注解类型 @MyAnnotation
- 注解编译之后也是生成class文件,生成
- 在注解当中,可以给注解类型定义属性;
- 定义属性的语法有点像方法,但它不是方法,叫做属性;
- 定义属性的语法: 属性类型 属性名();
- 注意:()中不能有任何属性; int age();
- 使用default关键字可以给属性定义默认值;
public @interface MyAnnotation {
// age属性,类型是int
int age();
// name属性,类型是String
String name();
// 添加了默认值,在使用注解时可以不写该属性
String color() default "red";
}
三 自定义注解类型 @MyAnnotation2
注解属性的数据类型可以是哪些? 属性的类型只能是以下类型之一:
- byte shout int long float double boolean char String 枚举 Class 注解 以及以上类型的数组形式;
- 包括8种数据类型、String、枚举、Class、注解以及以上类型的数组形式;
public @interface MyAnnotation2 {
boolean sex() default true;
char gender();
String name();
// Class类型
Class type();
// 枚举类型
Color yanSe() default Color.BLUE;
// 数组类型
String[] values();
}
四 自定义注解类型 @MyAnnotation3
注解名为“value”时,使用时可以省略注解名;
@MyAnnotation3(value = “zz”) 和 @MyAnnotation3(“zz”) 效果相同
public @interface MyAnnotation3 {
String value();
}
五 自定义注解类型 @MyAnnotation4
数组中如果只有一个元素,使用属性时,{}可以省略;
@MyAnnotation4(names = {“jack”}) 和 @MyAnnotation4(names = “jack”)效果相同
public @interface MyAnnotation4 {
String[] names();
}
六 使用自定义的注解类
public class AnnotationTest05 {
@MyAnnotation(age = 2, name="aa")
public static void main(String[] args) {
}
// 属性值是数组时,{}必须写
@MyAnnotation2(sex = false,
gender = '女',
name = "asd",
type = Date.class,
yanSe = Color.RED,
values = {"a", "b"})
public static void doSome(){}
// 注解名为“value”时,使用时可以省略注解名
// @MyAnnotation3(value = "zz")
@MyAnnotation3("zz")
public void doOther(){}
// 数组中如果只有一个元素,使用属性时,{}可以省略;
// @MyAnnotation4(names = {"jack"})
@MyAnnotation4(names = "jack")
public void m(){}
}