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.
Not every language supports reflection, but the principles are usually the same in languages that support it.
Reflection is the ability to "reflect" on the structure of your program. Or more concrete. To look at the objects and classes you have and programmatically get back information on the methods, fields, and interfaces they implement. You can also look at things like annotations.
It's useful in a lot of situations. Everywhere you want to be able to dynamically plug in classes into your code. Lots of object relational mappers use reflection to be able to instantiate objects from databases without knowing in advance what objects they're going to use. Plug-in architectures is another place where reflection is useful. Being able to dynamically load code and determine if there are types there that implement the right interface to use as a plugin is important in those situations.
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.
<bean id="someID" class="com.example.Foo">
<property name="someField" value="someValue" />
</bean>
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);
Reflection
has many uses. The one I am more familiar with, is to be able to create code on the fly.
IE: dynamic classes, functions, constructors - based on any data (xml/array/sql results/hardcoded/etc..)
I want to answer this question by example. First of all Hibernate
project uses Reflection API
to generate CRUD
statements to bridge the chasm between the running application and the persistence store. When things change in the domain, the Hibernate
has to know about them to persist them to the data store and vice versa.
Alternatively works Lombok Project
. It just injects code at compile time, result in code being inserted into your domain classes. (I think it is OK for getters and setters)
Hibernate
chose reflection
because it has minimal impact on the build process for an application.
And from Java 7 we have MethodHandles
, which works as Reflection API
. In projects, to work with loggers we just copy-paste the next code:
Logger LOGGER = Logger.getLogger(MethodHandles.lookup().lookupClass().getName());
Because it is hard to make typo-error in this case.
Reflection allows instantiation of new objects, invocation of methods, and get/set operations on class variables dynamically at run time without having prior knowledge of its implementation.
Class myObjectClass = MyObject.class;
Method[] method = myObjectClass.getMethods();
//Here the method takes a string parameter if there is no param, put null.
Method method = aClass.getMethod("method_name", String.class);
Object returnValue = method.invoke(null, "parameter-value1");
In above example the null parameter is the object you want to invoke the method on. If the method is static you supply null. If the method is not static, then while invoking you need to supply a valid MyObject instance instead of null.
Reflection also allows you to access private member/methods of a class:
public class A{
private String str= null;
public A(String str) {
this.str= str;
}
}
.
A obj= new A("Some value");
Field privateStringField = A.class.getDeclaredField("privateString");
//Turn off access check for this field
privateStringField.setAccessible(true);
String fieldValue = (String) privateStringField.get(obj);
System.out.println("fieldValue = " + fieldValue);
java.lang.reflect
). Class metadata can be accessed through java.lang.Class
.Reflection is a very powerful API but it may slow down the application if used in excess, as it resolves all the types at runtime.
As name itself suggest it reflects what it holds for example class method,etc apart from providing feature to invoke method creating instance dynamically at runtime.
It is used by many frameworks and application under the wood to invoke services without actually knowing the code.