A Hidden Class is a special type of dynamically generated class introduced in Java 15. It is designed for internal JVM and framework usage and cannot be discovered through normal class loading mechanisms. Hidden classes are typically created at runtime and are intended for short-lived operations such as proxies, lambda implementations, and bytecode generation frameworks.
Key Points: • Hidden classes are not accessible through normal class lookups and are not intended to be used directly by application code. • They help frameworks generate temporary runtime classes without polluting the class namespace or classpath. • Hidden classes improve memory management and reduce class loader retention issues in applications that generate many dynamic classes.
Example: Frameworks such as dependency injection containers, ORM tools, proxy generators, and lambda implementations often need to create classes dynamically. Using hidden classes allows these generated classes to remain internal and disposable without affecting the application's visible class hierarchy.
Code Example:
import java.lang.invoke.MethodHandles;
public class HiddenClassDemo {
public static void main(String[] args)
throws Exception {
MethodHandles.Lookup lookup =
MethodHandles.lookup();
// Hidden classes are typically created
// using Lookup.defineHiddenClass()
System.out.println(
"Hidden classes are generated dynamically at runtime");
}
}Interview Tip: A concise interview answer is: Hidden Classes, introduced in Java 15, are dynamically generated, non-discoverable classes primarily used by frameworks and the JVM. They are ideal for runtime-generated implementations such as proxies and lambda expressions because they reduce classpath pollution, improve memory efficiency, and help prevent class loader-related memory leaks.