使用 JavaParser 更改方法级别的字符串变量
Change method level String variables with JavaParser
我想使用 JavaParser 将 Java 源代码中的所有字符串变量值从任何值更改为 ""
。
我可以更改全局变量的值,但无法更改方法级变量的值。
环顾四周,我从 this and 个答案中得到了帮助,现在我可以获取每个方法中每一行代码的值,如下所示:
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?
}
}
}
}
}
}
现在,如果 tmp
是字符串声明,我该如何更改它的值?
你是这个意思吗?
static void removeStrings(CompilationUnit cu) {
cu.walk(StringLiteralExpr.class, e -> e.setString(""));
}
测试
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);
输出
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);
}
}
我想使用 JavaParser 将 Java 源代码中的所有字符串变量值从任何值更改为 ""
。
我可以更改全局变量的值,但无法更改方法级变量的值。
环顾四周,我从 this and
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?
}
}
}
}
}
}
现在,如果 tmp
是字符串声明,我该如何更改它的值?
你是这个意思吗?
static void removeStrings(CompilationUnit cu) {
cu.walk(StringLiteralExpr.class, e -> e.setString(""));
}
测试
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);
输出
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);
}
}