Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dha-lo-jd/9669108 to your computer and use it in GitHub Desktop.
Save dha-lo-jd/9669108 to your computer and use it in GitHub Desktop.
import java.lang.annotation.Annotation;
import java.util.EnumSet;
import com.google.common.collect.Lists;
public class AnnotationRecursiveDigger {
public interface Function<A extends Annotation> {
void work(Class<?> cls, Class<?> superCls, A anno);
}
public enum Target {
SuperClass, Interface,
}
public static <A extends Annotation> void processAnnotationDeep(Class<?> cls, Class<A> annotation, Class<?> targetCls, Function<A> function,
EnumSet<Target> targets) {
if (targets.contains(Target.SuperClass)) {
Class<?> superCls = targetCls.getSuperclass();
if (superCls != null) {
processAnnotationDeep(cls, annotation, superCls, function, targets);
}
}
if (targets.contains(Target.Interface)) {
for (Class<?> superCls : targetCls.getInterfaces()) {
processAnnotationDeep(cls, annotation, superCls, function, targets);
}
}
A anno = targetCls.getAnnotation(annotation);
if (anno != null) {
function.work(cls, targetCls, anno);
}
}
public static <A extends Annotation> void processAnnotationDeep(Class<?> cls, Class<A> annotation, Function<A> function, Target... targetArgs) {
if (targetArgs == null || targetArgs.length == 0) {
targetArgs = Target.values();
}
EnumSet<Target> targets = EnumSet.copyOf(Lists.newArrayList(targetArgs));
processAnnotationDeep(cls, annotation, cls, function, targets);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment