Suppose I have the following snippet of code
class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
if (yes(1) == true) {
System.out.println("yep");
//do something
}
List <Integer> myList = new ArrayList();
if (myList.size() > 1) {
// do something
}
if (myList.isEmpty() == true) {
//do something else
}
}
static boolean yes(int choice) {
if (choice == 1) {
return true;
}
return false;
}
}
I intend to find out the values returned by the statement myList.isEmpty() in the if statement. I could evaluate the value of the variable returned by yes() which is a boolean , using calculateResolvedType() method in javaparser. When i tried to evaluate the value returned by myList.isEmpty(), it throws an UnsolvedSymbolException, though the types of both myList.isEmpty() and yes() are MethodCallExpr. Could you please help me how to get the value returned by a MethodCallExpr, when the method is called from a non static context ?
Here is what I tried so far:
public void avoidBooleanIfComparison() throws IOException {
ParserConfiguration config = new ParserConfiguration();
config.setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver(false)));
StaticJavaParser.setConfiguration(config);
FileInputStream in = new FileInputStream("src/main/resources/OptimiserInput.java");
CompilationUnit cu;
try {
// parse the file
cu = StaticJavaParser.parse(( in ));
} finally {
in .close();
}
for (BinaryExpr bex: cu.findAll(BinaryExpr.class)) {
System.out.println("Binary expression= " + bex.toString() + " left= " + bex.getLeft());
if (bex.getLeft() instanceof MethodCallExpr) {
Expression mce = bex.getLeft();
System.out.println("Trying to calculate type from " + mce.toString());
String type = mce.calculateResolvedType().describe(); // here is where the exception occurs
System.out.println("Type is " + type);
if (type.equals("boolean") && ((bex.getRight().toString().equals("true")) || (bex.getRight().toString().equals("false")))) {
System.out.println("avoid evaluating boolean in IfComparsion");
}
}
}
}
I aim to first isolate all BinaryExpr and then , if the left of it is a MethodCallExpr, then I aim to check the right . And if both are booleans, then I have to print, "Avoid Comparisons when LHS is Boolean". Thanks a lot for the help!
Your sample code does not compile. This is a prerequisite for using JavaParser. You must add the corresponding import to the "List" interface.