我尝试在这两行中运行方法setForStatement
:
cu.getNodesByType(ForStmt.class)
.forEach(Main::setForStatement);
我将hello-String放在代码的不同部分,以检查哪些部分有效。但方法setForStatement不运行,因为控制台上没有“hello5”行:
这是我的代码:
import javax.tools.*;
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
System.out.println("hello");
final String fileName = "Class.java";
final String alteredFileName = "src\\ClassAltered.java";
CompilationUnit cu;
try(FileInputStream in = new FileInputStream(fileName)){
cu = JavaParser.parse(in);
}
cu.getNodesByType(ForStmt.class)
.forEach(Main::setForStatement);
cu.getClassByName("Class").get().setName("ClassAltered");
try(FileWriter output = new FileWriter(new File(alteredFileName), false)) {
output.write(cu.toString());
}
System.out.println("hello2");
File[] files = {new File(alteredFileName)};
String[] options = { "-d", "out//production//Synthesis" };
System.out.println("hello3");
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null)) {
Iterable<? extends JavaFileObject> compilationUnits =
fileManager.getJavaFileObjectsFromFiles(Arrays.asList(files));
compiler.getTask(
null,
fileManager,
diagnostics,
Arrays.asList(options),
null,
compilationUnits).call();
System.out.println("hello4");
diagnostics.getDiagnostics().forEach(d -> System.out.println(d.getMessage(null)));
}
}
private static void setForStatement(ForStmt forStmt) {
System.out.println("hello5");
MethodCallExpr initializer = (MethodCallExpr) forStmt.getInitialization().get(0);
SimpleName name = initializer.getName();
if(!name.toString().equals("FOR")) {
if (initializer.getArguments().size() == 5
&& initializer.getArgument(0) instanceof NameExpr
&& initializer.getArgument(1) instanceof NameExpr
&& initializer.getArgument(2) instanceof IntegerLiteralExpr
&& initializer.getArgument(3) instanceof CharLiteralExpr
&& initializer.getArgument(4) instanceof CharLiteralExpr) {
NameExpr a1 = (NameExpr) initializer.getArgument(0);
NameExpr a2 = (NameExpr) initializer.getArgument(1);
IntegerLiteralExpr a3 = (IntegerLiteralExpr) initializer.getArgument(2);
CharLiteralExpr a4 = (CharLiteralExpr) initializer.getArgument(3);
CharLiteralExpr a5 = (CharLiteralExpr) initializer.getArgument(4);
}
}
}
}
答案 0 :(得分:1)
我假设您正在使用http://javaparser.org/中的库。如果我错了,请纠正我。
未调用方法setForStatement(...)
的原因仅仅是因为cu.getNodesByType(ForStmt.class)
返回空列表。您可以通过在代码中添加以下行来轻松验证这一点:
System.out.println("For statements: " + cu.getNodesByType(ForStmt.class).size());
如果你需要帮助找出为什么它会返回一个空列表,你真的需要提供mcve example。