Reputation: 2480
i am trying to implement the Custom Java Annotation : and wrote following so far:
@Target({ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MappedField{
boolean isValueRequired() default false;
}
My Requirement is if a property/Method of a Class is isValueRequired=true then it should get the mapped value for this property from database:
For example in my db Salutations are like 01 for MR and 02 for MRS and so on.
And when this annotation is enabled i want property value automatically to be fetched from db:
From other questions i got hint that i need to parse the annotations later something like this:
public static void performAnnotationScanOnClass(Class<?> clazz) {
Field[] fields = clazz.getDeclaredFields();
for ( Field field : fields ) {
Annotation[] annotations = field.getAnnotations();
for (Annotation annotation : annotations) {
if ( annotation instanceof MappedField) {
MappedField mappedField= (MappedField) annotation;
// if ( field.get( ... ) == null )
// field.set( ... , value)
}
but my point is where exactly i need to write this code for parsing the annotations. Any help would be highly appreciated.
Thanks
Upvotes: 0
Views: 397
Reputation: 73558
A suitable place. You could for example have a factory that creates the instances and fills the values from the database. Then you'll just need to be careful to create all the instances through the factory (or you don't need to, but then you must realize that the annotations won't be processed either).
Upvotes: 2