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
Post a Comment

Featured Post

Updated Coupons / promo codes for Google Apps for Work / Business

To redeem: 1. Sign up for Google Apps   2. Go to your billing settings  3. Choose your payment plan  4. Enter your promo code ...