JavaParser lib issue: ParseProblemException: Use of patterns with instanceof is not supported

183 Views Asked by At

I'm using the JavaParser library to parse Java source code in my project, and I recently encountered an issue when trying to parse code that includes Java 17 features. Specifically, I have expressions that involve instanceof with patterns, and I'm receiving the following error:

Exception in thread "main" com.github.javaparser.ParseProblemException: (line 56, col 42) Use of patterns with instanceof is not supported.

I need to parse Java source code that includes Java 17 features, and it seems that JavaParser is throwing an exception when it encounters instanceof with patterns.

I've tried following snippet for which I was getting this issue:

Here's a simplified code snippet that reproduces the issue:

public class JavaParserExample {
    public static void main(String[] args) throws Exception {
        // Load a Java source file
        File sourceFile = new File("MyClass.java");
        CompilationUnit compilationUnit = StaticJavaParser.parse(sourceFile);
        
        // Extract class information
        ClassOrInterfaceDeclaration classDeclaration = compilationUnit.getClassByName("MyClass").get();
        String className = classDeclaration.getNameAsString();

        // Extract method information
        for (MethodDeclaration method : classDeclaration.getMethods()) {
            String methodName = method.getNameAsString();
            String returnType = method.getType().asString();
            System.out.println("Method: " + methodName + ", Return Type: " + returnType);
        }

        // Print class information
        System.out.println("Class Name: " + className);
    }
}

Is there a way to configure JavaParser to handle Java 17 features like instanceof with patterns?

2

There are 2 best solutions below

1
Manan Prajapati On

Instead of using StaticJavaParser, we need to use configurable JavaParser as follow:

final ParserConfiguration parserConfiguration = new ParserConfiguration();
parserConfiguration.setLanguageLevel(ParserConfiguration.LanguageLevel.JAVA_17);

JavaParser javaParser = new JavaParser(parserConfiguration);

javaParser.parse(sourceFile);
0
jpl On

You can also use the JavaParserAdapter wrapper which allows you to handle the result in a simpler way. A ParseProblemException is thrown if there is a problem while parsing the source code.

JavaParser javaParser = new JavaParser(parserConfiguration);
JavaParserAdapter adapter = JavaParserAdapter.of(javaParser);
javaParser.parse(sourceFile);