How to check if a given line of code is written in java?

What is the correct way to check if a given string is java code?

Login : LogSupport.java:44 com / sun / activation / registries / LogSupport log (Ljava / lang / String;) V

Expected Result : false.

Input : scanner in = new scanner (System.in);

Expected Result : true.

I tried the Eclipse JDT ASTParser to check if we can create an AST. Here is the code:

public static boolean isJava(String line) { boolean isJava = false; ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setSource(line.toCharArray()); parser.setResolveBindings(false); ASTNode node = null; parser.setKind(ASTParser.K_STATEMENTS); try { node = parser.createAST(null); if (node == null) return false; isJava = true; } catch (Exception e) { return false; } return isJava; } 

But that does not work. Any ideas? Thanks!

+6
source share
2 answers

Try Beanshell

http://www.beanshell.org/intro.html

Java evaluation features:

Compute the complete Java source classes dynamically, as well as isolated Java methods, instructions, and expressions.

Feature Summary

Dynamic execution of the full Java syntax, fragments of Java code, as well as weakly typed Java and additional scripting capabilities.

Transparent access to all Java objects and APIs.

It works in four modes: Command Line, Console, Applet, Remote Session Server. It can work in an environment with security restrictions without generating a class or bytecode for most functions.

Interpreter is a small file with a size of 150K.

Pure Java.

It's free!!

There is another option in the link below that you could try

Java syntax checking

+4
source

What you want is to decide if the string you have is a valid substring of the Java language.

Obviously, for this you need a complete Java parser as the foundation. Some parsing mechanisms may allow you to parse a string as a nonterminal in a language; this is relatively easy to do with the recursive descent parser. (Eclipse parsing seems to suggest that based on the OP example).

But if you want to accept a substring (e.g.

  57).x=2; foo[15].bar(abc>= 

is a valid Java snippet, you need to develop mechanisms specialized in this.

Our DMS Software Reengineering Toolkit with its Java Front End will do this. The parser APIs provide tools for "parsing the full compilation unit", "parse non-terminal", and "parse substring". The first two return trees; the latter returns a sequence of trees. This is not a completely arbitrary substring; you cannot start or end in the middle of a token (for example, a string literal). In addition, it will parse arbitrary substrings.

+1
source

Source: https://habr.com/ru/post/985755/


All Articles