在运行时获取注释信息

hgu*_*ser 6 java annotations runtime hibernate-search

我想知道是否有任何方法可以在运行时获取类的注释信息?因为我想获得sepcifily注释的属性.

例:

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

    //..........getter and setter
}
Run Code Online (Sandbox Code Playgroud)

注释来自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;
}
Run Code Online (Sandbox Code Playgroud)

}

Sta*_*Man 2

是的当然。您的代码示例实际上并未获取类的注释信息,而是获取字段的注释信息,但代码类似。你只需要获取你感兴趣的类、方法或字段,然后调用“getAnnotation(AnnotationClass.class)”就可以了。

唯一需要注意的另一件事是注释定义必须使用正确的 RetentionPolicy,以便注释信息存储在字节代码中。就像是:

@Target({ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation { ... }
Run Code Online (Sandbox Code Playgroud)