Video in progress
What is a hidden class, and what has it changed for classes generated at runtime since Java 15?
A hidden class (JEP 371) is created with Lookup.defineHiddenClass. It can't be found by name and other classes can't link to it directly. It can be unloaded on its own, so it is safe and light on metaspace for the classes that lambdas, proxies and frameworks generate.
📖 Answer
Before, frameworks created dynamic classes in two ways: defineClass with their own ClassLoader, or the internal Unsafe.defineAnonymousClass. With the first, the class gets bound to the classloader and stays in metaspace until the loader is collected. The second was an unsupported internal API.
A hidden class:
MethodHandles.Lookup lookup = MethodHandles.lookup();
byte[] bytes = generateBytecode(); // ASM, ByteBuddy or the Class-File API
Class<?> c = lookup.defineHiddenClass(bytes, true).lookupClass();
Its properties:
- it can't be found with
Class.forName, and another class can't use it by name in bytecode, only through reflection or a method handle; - its name looks like
com.acme.Gen/0x0000000801001234(that is how you see it in a stack trace); - by default, once no references to it remain, it can be unloaded regardless of the classloader;
- with
ClassOption.NESTMATEit can access the private members of the class that created it.
The JDK itself uses hidden classes for lambdas inside LambdaMetafactory (since JDK 15). Unsafe.defineAnonymousClass was removed in JDK 17, so old libraries (old ByteBuddy, Groovy, Nashorn) had to be updated.
The practical value: in systems that generate many classes at runtime (script engines, serialization libraries), hidden classes reduce the chance of a metaspace leak. For diagnostics, jcmd <pid> VM.classloader_stats shows the number of "hidden classes" separately.
Sign up to mark studied questions and save your progress.