I want to create custom annotation in java for DirtyChecking
. Like I want to compare two string values using this annotation and after comparing it will return a
First you need to mark if annotation is for class, field or method. Let's say it is for method: so you write this in your annotation definition:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DirtyCheck {
String newValue();
String oldValue();
}
Next you have to write let's say DirtyChecker
class which will use reflection to check if method has annotation and do some job for example say if oldValue
and newValue
are equal:
final class DirtyChecker {
public boolean process(Object instance) {
Class> clazz = instance.getClass();
for (Method m : clazz.getDeclaredMethods()) {
if (m.isAnnotationPresent(DirtyCheck.class)) {
DirtyCheck annotation = m.getAnnotation(DirtyCheck.class);
String newVal = annotation.newValue();
String oldVal = annotation.oldValue();
return newVal.equals(oldVal);
}
}
return false;
}
}
Cheers, Michal