我想在java中创建自定义注释DirtyChecking.就像我想使用此注释比较两个字符串值,并在比较后将返回一个boolean值.
例如:我将放置@DirtyCheck("newValue","oldValue")属性.
假设我创建了一个界面:
public @interface DirtyCheck {
String newValue();
String oldValue();
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:
Mic*_*hal 20
首先,您需要标记注释是用于类,字段还是方法.让我们说它是方法:所以你在你的注释定义中写这个:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DirtyCheck {
String newValue();
String oldValue();
}
Run Code Online (Sandbox Code Playgroud)
接下来你要编写让我们说的DirtyChecker类,它将使用反射来检查方法是否有注释并做一些工作,例如说if oldValue和newValue是否相等:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
干杯,米哈尔
| 归档时间: |
|
| 查看次数: |
14091 次 |
| 最近记录: |