Working with Reflection

1. Getting Class Objects

FormDetail
obj.getClass()Runtime type
String.classClass literal
Class.forName("com.x.Foo")Dynamic load

2. Inspecting Class Information

MethodReturns
getName / getSimpleName / getCanonicalNameNames
getSuperclass / getInterfacesType hierarchy
getModifiers()int (use Modifier.isPublic(m))
getPackage / getModuleContainer info

3. Working with Fields

Example: Field access

Field f = User.class.getDeclaredField("email");
f.setAccessible(true);
String email = (String) f.get(user);
f.set(user, "new@x.com");
MethodReturns
getFields()Public fields (incl. inherited)
getDeclaredFields()All fields of this class
getDeclaredField(name)Single field

4. Working with Methods

MethodUse
getMethod(name, paramTypes...)Public method
getDeclaredMethod(...)Including non-public
m.invoke(target, args...)Call
Static callm.invoke(null, args)

5. Working with Constructors

MethodUse
getConstructor(types)Get
ctor.newInstance(args)Instantiate
cls.getDeclaredConstructors()All

6. Creating Instances Dynamically

FormDetail
cls.getDeclaredConstructor().newInstance()Modern way (Java 9+)
cls.newInstance()Deprecated

7. Invoking Methods Dynamically

AspectDetail
ReturnsObject (cast required)
ThrowsInvocationTargetException wraps the actual exception
PerformanceSlower than direct call; cache Method objects

8. Accessing Private Members

MethodDetail
setAccessible(true)Bypass access check
Module-protectedRequires --add-opens for JDK internals
RecordsComponents accessible via getRecordComponents()
Warning: Reflection breaks encapsulation and module boundaries — use sparingly.

9. Working with Generic Types

MethodReturns
getGenericType()Field's generic type (Type)
getGenericReturnType()Method's generic return
ParameterizedTypeCast to extract type args
NoteErasure removes type info from instances; only declarations remain

10. Using Class.forName()

OverloadDetail
forName(name)Initialize, default classloader
forName(name, init, cl)Control init + classloader

11. Using ClassLoader

TypeLoads
BootstrapCore JDK classes
PlatformJava SE platform modules
App (system)Classpath
CustomExtend ClassLoader

12. Understanding Reflection Performance

OptimizationDetail
Cache lookupsReuse Field/Method instances
MethodHandlesFaster alternative (java.lang.invoke)
VarHandlesFor field access
JITOptimizes hot reflective calls

13. Using MethodHandles API

Example: MethodHandle

MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodType mt = MethodType.methodType(String.class, int.class, int.class);
MethodHandle mh = lookup.findVirtual(String.class, "substring", mt);
String s = (String) mh.invoke("hello world", 0, 5);   // "hello"
ClassUse
MethodHandles.LookupAccess enforcement context
MethodTypeSignature description
MethodHandleTyped function reference (faster than Method.invoke)
VarHandleAtomic field operations