Skip to content

NoSuchMethodError when formatting with JDK 21 #885

Description

@gnodet

What happened?

When compiling maven master branch using JDK 21, I have the following exception:

Caused by: java.lang.NoSuchMethodError: 'com.sun.tools.javac.tree.JCTree com.sun.tools.javac.tree.JCTree$JCImport.getQualifiedIdentifier()'
	at com.palantir.javaformat.java.RemoveUnusedImports.getSimpleName(RemoveUnusedImports.java:245)
	at com.palantir.javaformat.java.RemoveUnusedImports.buildReplacements(RemoveUnusedImports.java:225)
	at com.palantir.javaformat.java.RemoveUnusedImports.removeUnusedImports(RemoveUnusedImports.java:209)
	at com.diffplug.spotless.glue.pjf.PalantirJavaFormatFormatterFunc.apply(PalantirJavaFormatFormatterFunc.java:42)

What did you want to happen?

The formatting should work !

Analysis

The getSimpleName method needs to adapted somehow. The JDK internal class JCImport has changed recently. In JDK 17, the method was defined as:

public JCTree getQualifiedIdentifier() { return qualid; }

and in JDK 21:

public JCFieldAccess getQualifiedIdentifier() { return qualid; }

One possibility to fix that would be to fix the getSimpleName() method to use an argument of type com.sun.source.tree.ImportTree and call the getQualifiedIdentifier() method which returns a com.sun.source.tree.Tree and has not changed.

    private static String getSimpleName(ImportTree importTree) {
        return importTree.getQualifiedIdentifier() instanceof JCIdent
                ? ((JCIdent) importTree.getQualifiedIdentifier()).getName().toString()
                : ((JCFieldAccess) importTree.getQualifiedIdentifier())
                        .getIdentifier()
                        .toString();
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions