Spring 3.0无法在运行时获取自定义Annotation

时间:2011-10-21 08:34:56

标签: java spring annotations runtime spring-3

我正在使用spring并尝试向Entity-Bean添加自定义Annotation。 我想做的就是通过反射访问带有自定义注释@ runtime的字段。 问题是,尽管字段上有多个Annotation,但在运行时都无法访问它们:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ChangeableField {

}

实体:

public class Order {

    @NotNull
    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(pattern = "dd:MM:yyyy HH:mm")
    @ChangeableField
    private Date scheduledStart;

    @NotNull
    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(pattern = "dd:MM:yyyy HH:mm")
    @ChangeableField
    private Date scheduledEnd;

    //...
}

我完全不知道该怎么做

Order.class.getField("scheduledStart").getAnnotation(ChangableField.class);

总是返回null。 (顺便说一下,这个字段上所有声明的注释都是空的)

也许它与春天有关?

我将不胜感激任何帮助!

提前致谢

修改

我不知道为什么,但现在它正常运作:

for (Field currentField : order.getClass().getDeclaredFields()) {
    if (currentField.getAnnotation(ChangeableField.class) != null
    && map.containsKey(currentField.getName())) {
         //..

感谢您的帮助

顺便说一句,这篇文章只是一个错字。

2 个答案:

答案 0 :(得分:2)

试试这个:

Order.class
     .getDeclaredField("scheduledStart")
     .getAnnotation(ChangableField.class);

Class.getField(fieldname)检索该类的公共字段和所有超类。您的字段是私有的,因此您需要Class.getDeclaredField(fieldname),它会检索所有可见性的字段,但仅限于此类。

答案 1 :(得分:0)

您的注释属于“ChangeableField”类,但您正在检索“ChangableField”(请注意缺少“e”)。这只是帖子中的拼写错误,还是你没有找回你的想法?