スプリングの独自アノテーションを定義の方法
カスタムアノテーションを定義するには、以下の手順に従います。
- インターフェース
public @interface MyAnnotation {
// 定义注解的成员变量
String name() default "";
int age() default 0;
}
- 私の注釈
@MyAnnotation(name = "John", age = 25)
public class MyClass {
// ...
}
- コードではリフレクションによってアノテーションの情報を取得できます。例えば、
Class<MyClass> myClass = MyClass.class;
if (myClass.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation annotation = myClass.getAnnotation(MyAnnotation.class);
String name = annotation.name();
int age = annotation.age();
// ...
}
これでカスタムアノテーションの作成と使用方法が完了します。カスタムアノテーションのインスタンス変数には既定値を設定できますが、既定値は指定されない場合があり、既定値はdefaultキーを使用して設定する必要があります。