使用 XPath 进行 PMD,有没有办法在方法调用中计算变量的值?

问题描述 投票:0回答:1

例如:

String user = "Daniel";
String result = doSomething(user);

我知道我可以用

doSomething(user)
找到
//MethodCall[@MethodName = "doSomething"]/ArgumentList/VariableAccess[@Name = "user"]
的每一次出现。是否有可能只找到那些
user
评估为“Daniel”的事件?

java eclipse xpath pmd
1个回答
0
投票

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"/>
© www.soinside.com 2019 - 2024. All rights reserved.