独自のアノテーションを作成して、独自のクラスに適用できます。
注釈を実行時に検出可能に指定すると、リフレクションを使用して簡単に処理できます。
たとえば、次のようなものを使用して、Funkyアノテーションでマークされたクラスの各フィールドの名前を出力できます。
for (Field someField : AnnotatedClass.getClass().getDeclaredFields()) {
if (someField.isAnnotationPresent(Funky.class)) {
System.out.println("This field is funky: " + someField.getName());
}
}
ファンキーアノテーションを宣言するコードは次のようになります。
package org.foo.annotations;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Funky { }
アノテーションを使用するクラスは次のとおりです。
package org.foo.examples;
import org.foo.annotations.Funky;
public class AnnotatedClass {
@Funky
private String funkyString;
private String nonFunkyString;
@Funky
private Integer funkyInteger;
private Integer nonFunkyInteger;
}
アノテーションについてもう少し読んでください。
上記で使用したクラスのjavadocは次のとおりです。
私はあなたの車の例を理解しようとしていますが、あなたが望むものに従うかどうかはわかりません。
車を拡張し、さまざまな車関連の注釈でマークされたオブジェクト(ジャガー、ポルシェ、フェラーリ、起亜)のリストがある場合は、注釈に基づいてリストをフィルタリングするオブジェクトを作成できます。
コードは次のようになります。
@WorldsFinestMotorCar
class Jaguar extends Car {
// blah blah
}
@BoringCar
class Porche extends Car {
// blah blah
}
@BoringCar
class Ferrari extends Car {
// blah blah
}
@IncredibleCar
class Kia extends Car {
// blah blah
}
特定の注釈がない車をリストから削除 するAnnotationFilterクラスを実装できます。
次のようになります。
List<Car> carList = getListOfRandomCars();
AnnotationFilter<Car> annoFilter = new AnnotationFilter<Car>(BoringCar.class);
List<Car> boringCars = annoFilter.filter(carList);
それはあなたがやりたいことですか?
もしそうなら、それは間違いなく行うことができます。
AnnotationFilterの実装は、次のようになります。
public class AnnotationFilter<T> {
private Class filterAnno;
public AnnotationFilter(Class a) {
filterAnno = a;
}
public List<T> filter(List<T> inputList) {
if (inputList == null || inputList.isEmpty()) {
return inputList;
}
List<T> filteredList = new ArrayList<T>();
for (T someT : inputList) {
if (someT.getClass().isAnnotationPresent(filterAnno)) {
filteredList.add(someT);
}
}
return filteredList;
}
}
それがあなたが求めているものではない場合は、特定の例が役立ちます。