在运行时获取的注释信息

编程入门 行业动态 更新时间:2024-10-26 02:27:19
本文介绍了在运行时获取的注释信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我不知道是否有什么办法可以在运行时类的注释信息?因为我想要得到sepcifily注释的属性。

I wonder if there is any way I can get the annotation information of a class at runtime? Since I want to get the properties that sepcifily annotated.

例如:

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

注解来自休眠搜索,现在我想的就是其中的TestMain的属性的注释作为一个田(在这个例子中,他们的 [姓名,年龄] ),而这是存储(存储= store.yes)(在本例中,它们是[年龄])在运行时。

The annotations come from the hibernate-search,and now what I want is get which property of the "TestMain" is annotated as a 'field'(in the example,they are [name,age]),and which is 'stored(store=store.yes)'(in the example,they are [age]) at runtime.

任何想法?

更新:

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; }

}

推荐答案

是的,当然。您code样品实际上并没有得到一流的注释信息,但对于字段,但code是相似的。你只需要得到你类,方法或字段有兴趣,然后调用getAnnotation(AnnotationClass.class)就可以了。

Yes, of course. Your code sample does not actually get annotation information for class, but for fields, but code is similar. You just need to get Class, Method or Field you are interested in, then call "getAnnotation(AnnotationClass.class)" on it.

其他唯一要注意的是,标注定义必须使用正确的RetentionPolicy,这样的注释信息存储在字节code。是这样的:

The only other thing to notice is that annotation definition must use proper RetentionPolicy so that annotation information is stored in byte code. Something like:

@Target({ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotation { ... }

更多推荐

在运行时获取的注释信息

本文发布于:2023-11-15 23:19:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1598849.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:注释   信息

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!