[英]Change method level String variables with JavaParser
I want to use JavaParser in order to change all String variable values in a Java source code from any value to ""
. 我想使用JavaParser来将Java源代码中的所有String变量值从任何值更改为
""
。
I can change the value of the global variables, but I cannot manage to change the value of the method level variables. 我可以更改全局变量的值,但是无法管理方法级变量的值。
Looking around, I got help from this and this answers and now I can get the value of every line of code in each method, like so: 环顾四周,我从这个和这个答案中得到了帮助,现在我可以获得每个方法中每一行代码的值,如下所示:
static void removeStrings(CompilationUnit cu) {
for (TypeDeclaration typeDec : cu.getTypes()) {
List<BodyDeclaration> members = typeDec.getMembers();
if (members != null) {
for (BodyDeclaration member : members) {
if (member.isMethodDeclaration()) { // If it is a method variable
MethodDeclaration method = (MethodDeclaration) member;
Optional<BlockStmt> block = method.getBody();
NodeList<Statement> statements = block.get().getStatements();
for (Statement tmp : statements) {
// How do I change the values here?
}
}
}
}
}
}
Now, how do I change the values of tmp
if it is a String declaration? 现在,如果它是String声明,如何更改
tmp
的值?
Do you mean like this? 你是这个意思吗
static void removeStrings(CompilationUnit cu) {
cu.walk(StringLiteralExpr.class, e -> e.setString(""));
}
Test 测试
CompilationUnit code = JavaParser.parse(
"class Test {\n" +
"private static final String CONST = \"This is a constant\";\n" +
"public static void main(String[] args) {\n" +
"System.out.println(\"Hello: \" + CONST);" +
"}\n" +
"}"
);
System.out.println("BEFORE:");
System.out.println(code);
removeStrings(code);
System.out.println("AFTER:");
System.out.println(code);
Output 输出量
BEFORE:
class Test {
private static final String CONST = "This is a constant";
public static void main(String[] args) {
System.out.println("Hello: " + CONST);
}
}
AFTER:
class Test {
private static final String CONST = "";
public static void main(String[] args) {
System.out.println("" + CONST);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.