Java reflection example

Reflection is the ability of a computer program to examine and modify the structure and behavior (specifically the values, meta-data, properties and functions) of an object at runtime.

Type Introspection (instanceof) is the ability to inspect the code in the system and see object types. Reflection is then the ability to make modifications at runtime by making use of introspection.

The sample code can be download here.



Use reflection to deal with private property or method such as unit testing:
/// For private methods:

Method method = targetClass.getDeclaredMethod(methodName, argClasses);
return method.invoke(targetObject, argObjects);

/// And for private fields:

Field field = targetClass.getDeclaredField(fieldName);
field.set(object, value);
// The setAccessible(true) is required to play around with privates.
Reflection tutorial

Featured Post

NGINX Unit is dynamically configured using a REST API

There is no static configuration file. All configuration changes happen directly in memory. Configuration changes take effect without requir...