我遇到了来自here的类似问题,其中lambda表达式中的类型绑定未针对MethodInvocation
类型正确解析。
目前正在使用版本' 3.13.50'并尝试使用' 3.13.100'这是Eclipse 4.7.3似乎使用的。很高兴尝试任何调试;目前难以理解,因为其他类型绑定正确解析(对于ImportDeclaration
语句和未包含在lambda表达式中的表达式)。
解析器设置代码(parserClasspath
包含所有第三方库类(包括需要解析其类型绑定的域对象)的根路径,parserSourcepath
包含项目源文件的根目录):
char[] sourceInput = source.get().toCharArray();
ASTParser parser = ASTParser.newParser(AST.JLS9);
parser.setEnvironment(parserClasspath, parserSourcepath, null, false);
parser.setResolveBindings(true);
parser.setBindingsRecovery(true);
parser.setSource(sourceInput);
parser.setUnitName(projFilepath);
return parser.createAST(null);
解析器变换器片段(使用ASTVisitor):
@Override
public boolean visit(MethodInvocation mi) {
if (mi.getExpression() != null) {
// resolves to null when 'mi' is within lambda functions
ITypeBinding typeBinding = mi.getExpression().resolveTypeBinding();
if (typeBinding != null) {
// do stuff
}
}
return true;
}
解析示例:
private DomainType getMockDomainType() {
DomainType mock = mock(DomainType.class);
Supplier<DomainType> domainTypeSupplier = () -> {
DomainType domainType = mock(DomainType.class);
when(domainType.method()).thenReturn("VALUE");
...
return domainType;
};
DomainType domainType = domainTypeSupplier.get();
when(mock.method()).thenReturn(domainType)
...
return mock;
}
预期输出(method()
将转换为NEW_METHOD()
):
private DomainType getMockDomainType() {
DomainType mock = mock(DomainType.class);
Supplier<DomainType> domainTypeSupplier = () -> {
DomainType domainType = mock(DomainType.class);
when(domainType.NEW_METHOD()).thenReturn("VALUE");
...
return domainType;
};
DomainType domainType = domainTypeSupplier.get();
when(mock.NEW_METHOD()).thenReturn(domainType)
...
return mock;
}
实际输出:
private DomainType getMockDomainType() {
DomainType mock = mock(DomainType.class);
Supplier<DomainType> domainTypeSupplier = () -> {
DomainType domainType = mock(DomainType.class);
when(domainType.method()).thenReturn("VALUE");
...
return domainType;
};
DomainType domainType = domainTypeSupplier.get();
when(mock.NEW_METHOD()).thenReturn(domainType)
...
return mock;
}
在visit(MethodDeclaration mi)
的lambda表达式中的domainType.method()
方法中,mi.getExpression().resolveTypeBinding()
为null
时应该是DomainType
的绑定。