Reflection in Java and It’s Uses

Reflection in java is used to describe code which is able to examine or modify the run-time behavior of applications running in the Java virtual machine. Reflection in java is a powerful technique that enables applications to perform various operations which would be otherwise impossible.

We can inspect and dynamically call classes, interfaces, methods, and field’s information at runtime with the help of Reflection in java even though class is not accessible at compile time. For example IDEs like eclipse uses the reflection for auto completion of method names.

Example 1:- get class name using reflection

public class ReflectionTest {

     public static void main(String[] args){
	    Simple sim = new Simple();
        System.out.println(sim.getClass().getName());        
    }
}	 
class Simple {}

output:-

Simple

In the above example getClass method returns the runtime class of object.

reflection in java

import java.lang.reflect.Method;

public class ReflectionTest {
	
	public static void main(String[] args){
		Simple sim = new Simple();

		Method method;
		try {
			method = sim.getClass().getMethod("print", new Class<?>[0]);
			method.invoke(sim);
		} 
		catch (Exception e) {
			e.printStackTrace();
		}			
	}
}

class Simple {
	public void print() {
		System.out.println("calling method using reflection");
	}
}

Output:-

calling method using reflection

In the above example we are using the getMethod method which returns a Method object that reflects the public member method of the class or interface represented by Class object.

Some real example of Reflection

• IDEs like eclipse, IntelliJ uses auto completion of method names
• JAXB uses reflection for marshalling, unmarshaling
• Dependency framework uses reflection for injecting bean dependencies
• ORM frameworks like hibernate uses reflection for defining the relationship between entities and database schemas.
• JUnit uses reflection to parse @Test annotation to get and invoke the test methods.

Although Reflection is powerful but if it is possible to perform an operation without using reflection, then it is preferable to avoid it. Following points should be considered while accessing code via reflection.

• loss of compile-time type safety
• bugs due to refactoring
• slower performance

Leave a Comment