Skip to content

New check request: Unreachable methods in anonymous classes #5156

@kevinb9n

Description

@kevinb9n

Any non-override, non-private method in an anonymous class is at least "dodgy" and might fool a dead code detector.

Non-override methods are hard to reach from outside the class body itself. There are two kinds of anonymous class:

  • In a "class instance creation expression with class body", a non-override method is only reachable one of two ways:
    • calling it directly with the anonymous class expression itself as the receiver (new Object() { void foo() {} }.foo())
    • if the anonymous class expression is assigned to a local variable that uses var instead of an explicit type
  • In an "enum constant with class body", a non-override method is not usable from outside that body at all.

If such a method is marked public, that might prevent a dead-code detector from recognizing it can be cleaned up. It would probably be a good practice to always make it private. Unfortunately, those two weird cases for non-enum anonymous classes should probably be exempted.

No idea if this is worth investigating further, just realized this as another strange wart in the language.

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