/**
* Execute the supplied runnable once (in same thread) if the supplied method has the supplied annotation.
* This method supports inheritance of method annotations. If the supplied method overrides a superclass or
* implements an interface with the annotation the runnable will be executed. Even if the annotation is available
* from multiple levels of the class hierarchy the runnable will only execute once.
*
* @param meth The method to test
* @param r The runnable that will run depending on the annotation
* @param runIfPresent true to run when the annotation is found, false to run when it's not found.
* @param annotation The annotation we are looking for
*/
public void runIfMethodAnnotated(Method meth, Runnable r, boolean runIfPresent,
Class<? extends Annotation> annotation) {
if (!annotation.isAnnotationPresent(Inherited.class)) {
boolean annotationPresent = meth.isAnnotationPresent(annotation);
if (runIfPresent && annotationPresent || !runIfPresent && !annotationPresent) {
r.run();
}
} else {
Set<Class> classes = new HashSet<>();
Class<?> clazz = meth.getDeclaringClass();
collectInterfaces(classes, clazz);
while (clazz != Object.class) {
classes.add(clazz);
clazz = clazz.getSuperclass();
}
// now iterate all superclasses and interfaces looking for a method with identical signature that has
// the annotation in question.
boolean found = false;
for (Class<?> c : classes) {
try {
Method m = c.getMethod(meth.getName(), meth.getParameterTypes());
Annotation[] declaredAnnotations = m.getDeclaredAnnotations();
for (Annotation a : declaredAnnotations) {
found |= annotation == a.annotationType();
if (runIfPresent && found) {
r.run();
return;
}
}
} catch (NoSuchMethodException ignored) {
}
}
if (!runIfPresent && !found) {
r.run();
}
}
}
AnnotationUtil.java 文件源码
java
阅读 29
收藏 0
点赞 0
评论 0
项目:jesterj
作者:
评论列表
文章目录