Inspectopedia Help

Anonymous class may be a named 'static' inner class

Reports anonymous classes that may be safely replaced with static inner classes. An anonymous class may be a static inner class if it doesn't explicitly reference its enclosing instance or local classes from its surrounding method.

A static inner class does not keep an implicit reference to its enclosing instance. This prevents a common cause of memory leaks and uses less memory per class instance.

Since Java 18, only serializable anonymous classes keep an implicit reference to their enclosing instance, if this reference is not used. Therefore, when the module language level is Java 18 or higher, this inspection reports serializable classes only.

The quick-fix extracts the anonymous class into a named static inner class.

Example:

void sample() { Thread thread = new Thread(new Runnable() { @Override public void run() { } }); }

After the quick-fix is applied:

void sample() { Thread thread = new Thread(new Task()); } private static class Task implements Runnable { @Override public void run() { } }

Locating this inspection

By ID

Can be used to locate inspection in e.g. Qodana configuration files, where you can quickly enable or disable it, or adjust its settings.

AnonymousInnerClassMayBeStatic
Via Settings dialog

Path to the inspection settings via IntelliJ Platform IDE Settings dialog, when you need to adjust inspection settings directly from your IDE.

Settings or Preferences | Editor | Inspections | Java | Memory

Inspection Details

By default bundled with:

IntelliJ IDEA 2024.2, Qodana for JVM 2024.2,

Can be installed with plugin:

Java, 242.22892

Last modified: 11 September 2024