【发布时间】:2015-01-14 16:57:19
【问题描述】:
我是反思的新手。有什么方法可以检测在哪里调用了特定的方法?例如:
public class MyClass {
public static void method(){
//DO SOMETHING
}
}
public class Test {
public test(){
MyClass.method();
}
}
public class MyProcessor extends AbstractProcessor {
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
Method method = MyClass.class.getDeclaredMethod("method");
Class classWhereMethodIsInvoked = obtainClassWhereMethodIsInvoked(method);
}
public Class obtainClassWhereMethodIsInvoked(Method method) {
//here I want to search one class that invoke that method, in this case Test.class
}
}
这样的事情是可能的还是我要疯了?
【问题讨论】:
-
恐怕这种信息无法通过通常的反射 API 获得,它检索类和实例变量、方法签名等,但不是 实际 字节码(需要确定您的陈述出现在哪里)。为此,您需要Apache BCEL。
-
谢谢,我会调查 BCEL :)
-
我认为这是不可能的,因为一个方法可以从多个不同的类中调用。
-
我认为这并不难做到,可以通过使用常规的旧 JDK 搜索您的程序可以访问的类文件来完成。
标签: java reflection annotations