Java 中的语法检查

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11298856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 04:34:49  来源:igfitidea点击:

Syntax Checking in Java

javasyntax-checking

提问by Steven Morad

I am currently working on a program that has an embedded text editor. The users are supposed to type java code in the editor. The code typed into the editor is then made into a string. I just want something that would check for missing parenthesis or a try without a catch, etc. It doesn't need to be compiled. I've looked around quite a bit, but I'm still new to programming and can't implement some of the harder stuff.

我目前正在开发一个具有嵌入式文本编辑器的程序。用户应该在编辑器中输入 java 代码。然后将输入到编辑器中的代码制成字符串。我只是想要一些可以检查缺少括号或尝试没有捕获等的东西。它不需要编译。我环顾四周,但我还是编程新手,无法实现一些更难的东西。

So to make it shorter: I'm looking for some java package that will analyze code for syntax errors.

所以为了让它更短:我正在寻找一些java包来分析语法错误的代码。

回答by orangepips

As of Java 6 you can use JavaCompilerto compile the text and get back Diagnosticobjects that tell you what problems the file has (if any). So for your example you'd need to take the content of the editor and pass it to the JavaCompiler, run it, and report back any problems. Example that follows assumes editor text written out to a file.

从 Java 6 开始,您可以使用JavaCompiler编译文本并返回诊断对象,这些对象会告诉您文件有什么问题(如果有)。因此,对于您的示例,您需要获取编辑器的内容并将其传递给 JavaCompiler,运行它并报告任何问题。下面的示例假设编辑器文本写入文件。

Example code:

示例代码:

File to Check

要检查的文件

public class HelloBuggyWorld {
    String test // missing a semicolon

    public static void main (String [] args) {
        System.out.println('Hello World!');  // should be double quoted
    }
}

Checker

检查器

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Formatter;
import java.util.List;
import java.util.Locale;

import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

public class JavaSyntaxChecker {
    public static void main(String[] args) {
        System.out.println(JavaSyntaxChecker.check("/path/to/HelloBuggyWorld.java"));
    }

    public static List<String> check(String file) {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

        StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
        Iterable<? extends JavaFileObject> compilationUnits =
                fileManager.getJavaFileObjectsFromStrings(Arrays.asList(file));

        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
        compiler.getTask(null, fileManager, diagnostics, null, null, compilationUnits).call();

        List<String> messages = new ArrayList<String>();
        Formatter formatter = new Formatter();
        for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
            messages.add(diagnostic.getKind() + ":\t Line [" + diagnostic.getLineNumber() + "] \t Position [" + diagnostic.getPosition() + "]\t" + diagnostic.getMessage(Locale.ROOT) + "\n");
        }

        return messages;
    }
}

Output

输出

From running the mainmethod.

从运行该main方法。

[ERROR:  Line [5]    Position [124] HelloBuggyWorld.java:5: unclosed character literal
, ERROR:     Line [5]    Position [126] HelloBuggyWorld.java:5: ';' expected
, ERROR:     Line [5]    Position [131] HelloBuggyWorld.java:5: not a statement
, ERROR:     Line [5]    Position [136] HelloBuggyWorld.java:5: ';' expected
, ERROR:     Line [5]    Position [137] HelloBuggyWorld.java:5: unclosed character literal
]

回答by Coffee

This is pretty standard in Eclipseand Netbeans.

这在EclipseNetbeans 中非常标准。

If you want a nice, simple editor with parentheses-checks I'd vote for Sublime text.

如果你想要一个漂亮、简单的带有括号检查的编辑器,我会投票给Sublime text

回答by sperumal

You can look at Beanshellinterpreter. It can interpret Java code (both full source file and code fragments) and report errors on syntax.

你可以看看Beanshell解释器。它可以解释 Java 代码(包括完整的源文件和代码片段)并报告语法错误。

回答by Ashwinee K Jha

Assuming that you want to validate that user has input java code with correct syntax then you could invoke javac compiler directly from within your program.

假设您想验证用户是否输入了具有正确语法的 java 代码,那么您可以直接从您的程序中调用 javac 编译器。

public int com.sun.tools.javac.Main.compile(String[] args);

You need tools.jar in your class path.

您的类路径中需要 tools.jar。

回答by Lemon Tree

You can use JDTto parse and analyze source.

您可以使用JDT来解析和分析源代码。

That's scala example. It's easy to do the same with java:

那是 Scala 的例子。用java做同样的事情很容易:

val str = "..." // Checking source code
val parser : ASTParser = ASTParser.newParser(org.eclipse.jdt.core.dom.AST.JLS3)    
val options = JavaCore.getOptions.asInstanceOf[java.util.Map[Object, Object]]
options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_7)
options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_7)
options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_7)
parser.setCompilerOptions(options)
parser.setSource(str.toCharArray)
val cu: CompilationUnit = parser.createAST(null).asInstanceOf[CompilationUnit]

CompilationUnit has method getProblems(). It returns list of detailed problem reports.

CompilationUnit 有方法 getProblems()。它返回详细问题报告的列表。

回答by Meng Lu

I suggest 1) CheckSyntax, "a development tool to help programmers write Java code that adheres to a coding standard." It has many standard checks, and 2) FindBugs, "a program which uses static analysis to look for bugs in Java code."

我建议 1) CheckSyntax,“一种帮助程序员编写符合编码标准的 Java 代码的开发工具。” 它有许多标准检查,以及 2) FindBugs,“一个使用静态分析来查找 Java 代码错误的程序”。

回答by Matt

you can probably embed the eclipse syntax checker into your program.

您可以将 eclipse 语法检查器嵌入到您的程序中。