6

実行時にクラスの注釈情報を取得する方法はありますか? 特定のアノテーションが付けられたプロパティを取得したいので。

例:

class TestMain {
    @Field(
            store = Store.NO)
    private String  name;
    private String  password;
    @Field(
            store = Store.YES)
    private int     age;

    //..........getter and setter
}

注釈は hibernate-search から来て、今私が欲しいのは、「TestMain」のどのプロパティが「フィールド」として注釈が付けられているか(この例では[name,age] )、および「格納されている ( store=store.yes)'(例では [ age ]) 実行時に。

何か案は?

アップデート:

public class FieldUtil {
public static List<String> getAllFieldsByClass(Class<?> clazz) {
    Field[] fields = clazz.getDeclaredFields();
    ArrayList<String> fieldList = new ArrayList<String>();
    ArrayList<String> storedList=new ArrayList<String>();
    String tmp;
    for (int i = 0; i < fields.length; i++) {
        Field fi = fields[i];
        tmp = fi.getName();
        if (tmp.equalsIgnoreCase("serialVersionUID"))
            continue;
        if (fi.isAnnotationPresent(org.hibernate.search.annotations.Field.class)) {
            //it is a "field",add it to list.
            fieldList.add(tmp);

            //make sure if it is stored also
            Annotation[] ans = fi.getAnnotations();
            for (Annotation an : ans) {
                //here,how to get the detail annotation information
                //I print the value of an,it is something like this:
                //@org.hibernate.search.annotations.Field(termVector=NO, index=UN_TOKENIZED, store=NO, name=, boost=@org.hibernate.search.annotations.Boost(value=1.0), analyzer=@org.hibernate.search.annotations.Analyzer(impl=void, definition=), bridge=@org.hibernate.search.annotations.FieldBridge(impl=void, params=[]))

                //how to get the parameter value of this an? using the string method?split?
            }
        }

    }
    return fieldList;
}

}

4

2 に答える 2

2

はい、もちろん。コードサンプルは、実際にはクラスのアノテーション情報を取得しませんが、フィールドのアノテーション情報を取得しますが、コードは類似しています。興味のあるクラス、メソッド、またはフィールドを取得してから、「getAnnotation(AnnotationClass.class)」を呼び出すだけです。

その他の注意点は、注釈情報がバイトコードに格納されるように、注釈定義で適切なRetentionPolicyを使用する必要があることです。何かのようなもの:

@Target({ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation { ... }
于 2010-12-14T02:32:29.613 に答える