What is reflection, and why is it useful?
I\'m particularly interested in Java, but I assume the principles are the same in any language.
Java Reflection is quite powerful and can be very useful. Java Reflection makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.
A quick Java Reflection example to show you what using reflection looks like:
Method[] methods = MyObject.class.getMethods();
for(Method method : methods){
System.out.println("method = " + method.getName());
}
This example obtains the Class object from the class called MyObject. Using the class object the example gets a list of the methods in that class, iterates the methods and print out their names.
Exactly how all this works is explained here
Edit: After almost 1 year I am editing this answer as while reading about reflection I got few more uses of Reflection.
When the Spring context processes this < bean > element, it will use Class.forName(String) with the argument "com.example.Foo" to instantiate that Class.
It will then again use reflection to get the appropriate setter for the < property > element and set its value to the specified value.
For Private methods,
Method method = targetClass.getDeclaredMethod(methodName, argClasses);
method.setAccessible(true);
return method.invoke(targetObject, argObjects);
For private fields,
Field field = targetClass.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(object, value);