例如:
String user = "Daniel";
String result = doSomething(user);
我知道我可以用
doSomething(user)
找到 //MethodCall[@MethodName = "doSomething"]/ArgumentList/VariableAccess[@Name = "user"]
的每一次出现。是否有可能只找到那些 user
评估为“Daniel”的事件?
MethodCall
和VariableDeclarator
都是同一Block
元素的后代。可以用来匹配条件
//Block[//VariableDeclarator[@Name="user"]/StringLiteral[@ConstValue="LMC"]]//MethodCall[@MethodName = "detectMe"]/ArgumentList/VariableAccess[@Name = "user"]
此表达式查找包含变量
Block
的
user = "LMC"
元素
//Block[//VariableDeclarator[@Name="user"]/StringLiteral[@ConstValue="LMC"]]
会匹配类似的东西
public void useIt(){
String user = "LMC";
String result = detectMe(user);
}
作为通用方法,可以编写具有相关用例的测试类并使用
pmd
转储以供以后进行 XML 分析
pmd ast-dump --format xml --language java --file PMDSource.java > PMDSource.java.xml
然后使用任何 XPath 感知工具来测试表达式
xmllint --xpath '//Block[//VariableDeclarator[@Name="user"]/StringLiteral[@ConstValue="LMC"]]//MethodCall[@MethodName = "detectMe"]/ArgumentList/VariableAccess[@Name = "user"]' PMDSource.java.xml
结果
<VariableAccess AccessType="READ" CompileTimeConstant="false" Expression="true" Image="user" Name="user" ParenthesisDepth="0" Parenthesized="false"/>