Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring 3.0 cannot get custom Annotation at runtime [closed]

I am working with spring and tried to add a custom Annotation to an Entity-Bean. All I want to do is, accessing the fields with the custom annotation @ runtime via reflection. The Problem is, that although there are more than one Annotation on the fields, none of them are accessable at runtime:

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

}

The entity:

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;

    //...
}

I have absolutely no idea what to do

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

returns always null. (BTW all declared annotations on this field are null)

Maybe it has something to do with spring?

I would appreciate any help!

Thanks in advance

EDIT

I don't know why but now it's working properly:

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

Thanks for your help

BTW It was just a typo in this post here..

like image 682
Alexander Avatar asked Jul 19 '26 03:07

Alexander


1 Answers

Try this:

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

Class.getField(fieldname) retrieves public fields of the class and all super classes. Your field is private, so you need Class.getDeclaredField(fieldname), which retrieves fields of all visibilities, but limited to this class only.

like image 106
Sean Patrick Floyd Avatar answered Jul 22 '26 23:07

Sean Patrick Floyd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!