I'd like to implement an annotation for methods which will let me know where those annotated methods called, just like official @deprecated annotation.
How can I get the list of all calling methods for a given annotated method?
I'd like to implement an annotation for methods which will let me know where those annotated methods called, just like official @deprecated annotation.
How can I get the list of all calling methods for a given annotated method?
I think this question may help you:
To find this annotated method (from Arthur Ronald's answer):
use org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider
API
A component provider that scans the classpath from a base package. It then applies exclude and include filters to the resulting classes to find candidates.
ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(<DO_YOU_WANT_TO_USE_DEFALT_FILTER>); scanner.addIncludeFilter(new AnnotationTypeFilter(<TYPE_YOUR_ANNOTATION_HERE>.class)); for (BeanDefinition bd : scanner.findCandidateComponents(<TYPE_YOUR_BASE_PACKAGE_HERE>)) System.out.println(bd.getBeanClassName());
Or (from Jonathan's answer):
Google reflections:
https://github.com/ronmamo/reflections
Quick review:
- Spring solution is the way to go if you're using Spring. Otherwise it's a big dependency.
- Using ASM directly is a bit cumbersome.
- Using Java Assist directly is clunky too.
- Annovention is super lightweight and convenient. No maven integration yet.
- Google reflections pulls in Google collections. Indexes everything and then is super fast.
Update: If want to calling methods for a given annotated method, you should use AOP (Aspect Oriented Programming) and add @ Around or @ Before, for example something like this (I don't check this code):
public class Foo {
@YourAnnotation
public int power(int x, int p) {
return Math.pow(x, p);
}
}
@Aspect
public class MethodLogger {
@Around("execution(* *(..)) && @annotation(YourAnnotation)")
public Object around(ProceedingJoinPoint point) {
Logger.info(
"call by method" + MethodSignature.class.cast(point.getSignature()).getMethod().getName()
);
Object result = point.proceed();
return result;
}
}