在此代码中,prosseek.B#bar()方法调用prosseek.SuperA#foo()。
package prosseek;
public class SuperA {
int i = 0;
public void foo()
{
System.out.println(i);
}
}
public class B {
public void bar()
{
SuperA a = new SuperA();
a.foo();
}
}
我需要检测 bar() 中调用的 foo() 的类型。
我使用 ASTVisitor 检测 MethodInitation 代码 (a.foo()),但我不确定应该做什么才能从中获取 SuperA
类型。
ICompilationUnit icu = type.getCompilationUnit();
final ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(icu);
parser.setResolveBindings(true); // we need bindings later on
CompilationUnit unit = (CompilationUnit) parser.createAST(null);
unit.accept(new ASTVisitor() {
public boolean visit(MethodInvocation methodInvocation)
{
// ???
return false;
}
}
添加
我从 JDT 基础教程中得到了提示。
我尝试了以下代码:
IBinding binding = methodInvocation.resolveTypeBinding();
IType type = (IType)binding.getJavaElement();
if (type == null)
return false;
但是,我得到了 Binding.getJavaElement(); 的返回值 null;
最佳答案
您可能需要从表达式中获取类型,而不是获取MethodInitation的类型。我尚未对此进行测试,但这可能会有所帮助。
public boolean visit(MethodInvocation node) {
Expression exp = node.getExpression();
ITypeBinding typeBinding = node.getExpression().resolveTypeBinding();
System.out.println("Type: " + typeBinding.toString());
}
关于java - 找出JDT中调用的方法的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14428483/