What is the right way to check if given line is java code?
Input: LogSupport.java:44 com/sun/activation/registries/LogSupport log (Ljava/lang/String;)V
Expected Output: false.
Input: Scanner in = new Scanner(System.in);
Expected Output: true.
I tried Eclipse JDT ASTParser to check if we can create an AST. Here's 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 this does not work. Any ideas? Thanks!
A method is a block of code that performs a specific task. Suppose you need to create a program to create a circle and color it.
ValueRange. of(minValue, maxValue); range. isValidIntValue(x); it returns true if minValue <= x <= MaxValue - i.e. within the range.
Try Beanshell
http://www.beanshell.org/intro.html
Java evaluation features:
Evaluate full Java source classes dynamically as well as isolated Java methods, statements, and expressions.
Summary of features
Dynamic execution of the full Java syntax, Java code fragments, as well as loosely typed Java and additional scripting conveniences.
Transparent access to all Java objects and APIs.
Runs in four modes: Command Line, Console, Applet, Remote Session Server. Can work in security constrained environments without a classloader or bytecode generation for most features.
The interpreter is small ~150K jar file.
Pure Java.
It's Free!!
The link below has some other option you could try
Syntax Checking in Java
What you want apparantly is to decide if a string you have is a valid substring of the Java language.
Obviously, to do this, you need a full Java parser as a foundation. Some parsing machinery may let you try parsing the string as a nonterminal in the language; this is relatively easy to do with a recursive descent parser. (It appears the Eclipse parse offers that, based on OP's example).
But if you want to accept an substring (e.g,
57).x=2; foo[15].bar(abc>=
is a valid Java fragment, you need parsing machinery specialized to handle this.
Our DMS Software Reengineering Toolkit with its Java Front End will do this. The parser APIs provide facilities for "parse a full compilation unit", "parse a nonterminal", and "parse a substring". The first two return trees; the latter returns a sequence of trees. It isn't quite an arbitrary substring; you can't start or end in the middle of token (e.g., a string literal). Other than that, it will parse arbitrary substrings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With