首先,您需要标记注释是否用于类,字段或方法。假设它是针对方法的:所以你在你的注释定义中写这个:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DirtyCheck {
String newValue();
String oldValue();
}
接下来,你必须写一个类,它将使用反射来检查方法是否有注释并做一些工作,例如说如果 和 是否相等:DirtyCheckeroldValuenewValue
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;
}
}
干杯,米哈尔