Java Reflection
“Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in Java Virtual machine.” The concept is ofen mixed with introspecion.The following are their definitions from Wiki:
what is Introspection and reflection?
- Introspection is the ability of a program to examine the type or properties of an object at runtime.
- Relection is the ability of a program to examine and modify the structure and behavior of an object at runtime.
Why do we need reflection?
- Examine an object’s class at runtime
- Construct an object for a class at runtime
- Examine a class’s field adn method at runtime
- Invoke any method of an object at runtime
- Change accessibility flag of Constructor, Method,Field
- etc.
For example, JUnit use reflection to look through methods tagged with the @Test annotation, and then call those methods when running the unit test. (Here is a set of examples of how to use JUnit.)
For web frameworks, product developers define their own implementation of interfaces and classes and put is in the configuration files. Using reflection,it can quickly dynamically initialize the classes required.
For example ,Spring uses bean configuration such as1
2
3<bean id="someID" class="com.Foo">
<property name="someField" value="someValue"/>
</bean>
When the Spring context processes this
The same mechanism is also used for Servlet web application1
2
3
4<Servlet>
<Servlet-name>someServlet</Servlet-name>
<Servlet-class>com.Foo</Servlet-class>
<Servlet>
how to use reflection?
Example 1: Get Class name from object
1 | package myreflection; |
Output:
1 | myreflection.Foo |
Example 2:Invoke method on unknown object
For the code example blow ,image the types of an object is unknown.By using reflection,the code can use the object and find out if the object has a method called “print” and the call it.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22package myreflection;
import java.lang.reflect.Method;
public class ReflectionHelloWorld {
public static void main(String[] args){
Foo f = new Foo();
Method method;
try {
method = f.getClass().getMethod("print", new Class<?>[0]);
method.invoke(f);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Foo {
public void print() {
System.out.println("abc");
}
}
Example 3: Create object from Class instance
1 | package myreflection; |
Example 4: Get constructor and create instance
1 | package myreflection; |
Output:
1 | null |
Example 5: Change array size though reflection
1 | package myreflection; |
Output:
1 | Array length: 10 |