google / google/error-prone

New check request: Unreachable methods in anonymous classes

Open
#5,156 6 comments 4 reactions 0 assignees View on GitHub
Dominant language
Java
Stars
7.2k
Forks
820
Avg merge
5h 9m
Merged PRs (30d)
50

Description

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.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.