Ein Java-Programm auf Syntax prüfen mit einem Java-Programm

package com.JavaCommandChecker;

import javax.tools.*;

import java.io.StringWriter;

import java.net.URI;

import java.util.*;

public class JavaCommandChecker {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println(“Gib deinen Java-Code ein:”);

String input = scanner.nextLine();

checkJavaCommand(input);

scanner.close();

}

public static void checkJavaCommand(String command) {

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();

StringWriter writer = new StringWriter();

SimpleJavaFileObject fileObject = new SimpleJavaFileObject(URI.create(“string:///” + “Test.java”), JavaFileObject.Kind.SOURCE) {

@Override

public CharSequence getCharContent(boolean ignoreEncodingErrors) {

return command;

}

};

List<JavaFileObject> fileList = Collections.singletonList(fileObject);

JavaCompiler.CompilationTask task = compiler.getTask(writer, null, diagnostics, null, null, fileList);

boolean success = task.call();

if (!success) {

System.out.println(“Fehler beim Kompilieren des Java-Codes:”);

for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {

System.out.format(“Fehlermeldung: %s in Zeile %d%n”,

diagnostic.getMessage(null), diagnostic.getLineNumber());

}

} else {

System.out.println(“Der Java-Code ist syntaktisch korrekt.”);

}

}

}

Java, Programmieren

Kommentar verfassen