Digital Marketing

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


Popular posts from this blog

Fixed WSL sshd: no hostkeys available -- exiting

PowerMTA pmta command

How to fix: mv: failed to preserve ownership