vendredi 27 novembre 2015

getDeclaredField and Annotation

I am suing springframework validation to validate my applications. Currently I am passing my fieldname as a hardcoded string to the validator. This has caused a lot of issue, where if a fieldname in the model changes the validations would fail.

I have looked into reflection to get the filename from the model using getDeclaredField. This method however returns a list of files for that class and if I need to get a specific field I will have to pass the right index. Eg. fields[8].getName(). So if the positioning of the fields changes I will have an issue.

I am wondering if there is any other simpler way I can pass a specific fieldname to the rejectValue ? would a custom annotation work? Like

@firstName private String firstName;

then use getDeclaredAnnotations to get my fieldname?

Here is how I am doing it now.

private String firstName; private String lastName;

errors.rejectValue("lastName ", ValidationConstants.INVALID_NULL_OR_BLANK_CODE);

if I using reflection errors.rejectValue(fields[2].getName(), ValidationConstants.INVALID_NULL_OR_BLANK_CODE);

Thanks.





Aucun commentaire:

Enregistrer un commentaire