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.
output:
Hello goyun.info!
Hello goyun.info!
Hello it.goyun.info!
Use reflection to deal with private property or method such as unit testing:
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.
output:
Hello goyun.info!
Hello goyun.info!
Hello it.goyun.info!
Use reflection to deal with private property or method such as unit testing:
/// For private methods:Reflection tutorial
Method method = targetClass.getDeclaredMethod(methodName, argClasses);
method.setAccessible(true);
return method.invoke(targetObject, argObjects);
/// And for private fields:
Field field = targetClass.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(object, value);
// The setAccessible(true) is required to play around with privates.
Comments
Post a Comment