要自定义注解,可以按照以下步骤进行:
- 使用
@interface
关键字定义一个新的注解,例如:
public @interface MyAnnotation { // 定义注解的成员变量 String name() default ""; int age() default 0; }
- 在使用自定义注解时,可以通过
@MyAnnotation
来标注类、方法、字段等,同时可以为注解的成员变量指定值,例如:
@MyAnnotation(name = "John", age = 25) public class MyClass { // ... }
- 在代码中可以通过反射的方式获取注解的信息,例如:
ClassmyClass = MyClass.class; if (myClass.isAnnotationPresent(MyAnnotation.class)) { MyAnnotation annotation = myClass.getAnnotation(MyAnnotation.class); String name = annotation.name(); int age = annotation.age(); // ... }
这样就完成了自定义注解的创建和使用。需要注意的是,自定义注解的成员变量可以有默认值,也可以不指定,默认值必须使用default
关键字进行设置。