Working with Reflection API

1. Getting Class Objects

SourceSyntax
LiteralString.class
Instanceobj.getClass()
NameClass.forName("com.X")
Loadercl.loadClass("com.X")
Primitiveint.class, void.class

2. Inspecting Class Members

MethodVisibility
getFields()Public, including inherited
getDeclaredFields()All declared in this class
getMethods()Public, inherited
getDeclaredMethods()All declared
getConstructors / getDeclaredConstructorsSame pattern
getRecordComponents()Records (Java 16+)

3. Accessing Private Members (setAccessible)

AspectDetail
setAccessible(true)Bypasses Java access checks
Modules (JPMS)Requires opens directive
Java 17+Strong encapsulation by default
Override--add-opens java.base/java.lang=ALL-UNNAMED
Warning: Reflection on JDK internals throws InaccessibleObjectException on Java 17+. Use public APIs or VarHandle.

4. Invoking Methods Dynamically (Method.invoke)

StepCode
Lookupcls.getMethod("name", paramTypes)
Invokem.invoke(target, args)
StaticPass null as target
ExceptionsWraps in InvocationTargetException

5. Creating Instances (Constructor.newInstance)

APIUse
cls.getDeclaredConstructor(paramTypes).newInstance(args)Modern preferred
cls.newInstance() DEPRECATEDJava 9+
No-argMust exist; setAccessible for private

6. Modifying Field Values

MethodUse
field.get(obj)Read
field.set(obj, value)Write
Staticfield.get(null)
Primitive specializationsgetInt, setLong, etc.
Final fieldsJava 17+ rejects (use VarHandle)

7. Working with Annotations

APIElement
getAnnotation(A.class)Class/Method/Field
getDeclaredAnnotations()All declared
getParameterAnnotations()2D array per param

8. Inspecting Generic Types (getGenericType)

APIReturns
field.getGenericType()Type (could be ParameterizedType)
method.getGenericReturnType()Type
cls.getGenericSuperclass()Type with type args
Cast toParameterizedType.getActualTypeArguments()

9. Understanding Performance Implications

CostMitigation
LookupCache Method/Field instances
Access checkssetAccessible(true) once
Boxing/unboxingUse specialized methods
vs direct call~5–20× slower; JIT can inline cached refs
BetterMethodHandle / LambdaMetafactory

10. Using MethodHandles as Alternative

vs ReflectionMethodHandle
SpeedNear-native after JIT
Type safetyMethodType at lookup
AccessCaptured at lookup; checks once
UseHigh-frequency dynamic calls

Example: Lookup + invoke

MethodHandles.Lookup lk = MethodHandles.lookup();
MethodHandle mh = lk.findVirtual(String.class, "length", MethodType.methodType(int.class));
int n = (int) mh.invokeExact("hello"); // 5