openrewrite / rewrite-static-analysis

OpenRewrite recipes for identifying and fixing static analysis issues.
Apache License 2.0
31 stars 50 forks source link

`org.openrewrite.staticanalysis.FinalClass` is wrong for nested sub classes #372

Open Bananeweizen opened 1 week ago

Bananeweizen commented 1 week ago

org.openrewrite.staticanalysis.FinalClass works on wrong assumptions. A non-final class with no public constructor can have nested static sub classes, and in that case it cannot be made final.

What is the smallest, simplest way to reproduce the problem?

public class Reproducer {

    private Reproducer(final String name) {
        //...
    }

    public static final class Sub extends Reproducer {

        public Sub() {
            super("subclass");
        }
    }
}

What did you expect to see?

no change

What did you see instead?

final added to the top level class

Are you interested in contributing a fix to OpenRewrite?

Maybe. Have to look for how to get the information that there are nested sub classes.

timtebeek commented 1 week ago

Thanks for reporting this variant! To detect sub classes you can either expand this loop https://github.com/openrewrite/rewrite-static-analysis/blob/2163f0f05dd6fe7f4762e3486c8f16a9a5787036/src/main/java/org/openrewrite/staticanalysis/FinalClassVisitor.java#L72-L83

Or add a new JavaIsoVisitor<>() { ... } that overrides visitClassDeclaration, and visit on the outer classDeclaration.getBody() and set an AtomicBoolean if any matching nested class declarations are found.