Java 使用反射获取带注释的字段列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16585451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get list of fields with annotation, by using reflection
提问by user902383
I create my annotation
我创建我的注释
public @interface MyAnnotation {
}
I put it on fields in my test object
我把它放在我的测试对象的字段上
public class TestObject {
@MyAnnotation
final private Outlook outlook;
@MyAnnotation
final private Temperature temperature;
...
}
Now I want to get list of all fields with MyAnnotation
.
现在我想获取所有字段的列表MyAnnotation
。
for(Field field : TestObject.class.getDeclaredFields())
{
if (field.isAnnotationPresent(MyAnnotation.class))
{
//do action
}
}
But seems like my block do action is never executed, and fields has no annotation as the following code returns 0.
但似乎我的 block do 操作从未执行过,并且字段没有注释,因为以下代码返回 0。
TestObject.class.getDeclaredField("outlook").getAnnotations().length;
Is anyone can help me and tell me what i'm doing wrong?
有没有人可以帮助我并告诉我我做错了什么?
采纳答案by Zutty
You need to mark the annotation as being available at runtime. Add the following to your annotation code.
您需要将注释标记为在运行时可用。将以下内容添加到您的注释代码中。
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
}
回答by Mindaugas K.
/**
* @return null safe set
*/
public static Set<Field> findFields(Class<?> classs, Class<? extends Annotation> ann) {
Set<Field> set = new HashSet<>();
Class<?> c = classs;
while (c != null) {
for (Field field : c.getDeclaredFields()) {
if (field.isAnnotationPresent(ann)) {
set.add(field);
}
}
c = c.getSuperclass();
}
return set;
}