EnclosingMethod attribute

For a local or anonymous class, the class and method it is written in.

Appears on
class
Since
class file 49.0 (Java 5)
javac writes it
for local and anonymous classes
Needed by the JVM
no: it is for the class libraries (reflection), compilers or tools

Layout

TypeFieldWhat it holds
u2attribute_name_indexa Utf8: "EnclosingMethod"
u4attribute_lengthbytes after this field
u2class_indexthe enclosing class
u2method_indexa NameAndType for the enclosing method, or 0 if in an initialiser

What it is for

For a local or anonymous class, the class and method it is written in. Class.getEnclosingMethod() reads it.

How common it is

JDK 25.0.5's java.base has 689 EnclosingMethod attributes, in 689 of its 7,391 classes (689 on classs).

A real one, byte by byte

From EnumSwitch$1.class (compiled by javac 25), on the class:

OffsetBytesFieldValue
61110 bytesEnclosingMethod
61100 24attribute_name_index#36
61300 00 00 04attribute_length4
61700 25class_index#37
61900 00method_index#0

Open in the viewer

Specification: JVMS §4.7, The EnclosingMethod Attribute (Java SE 25).