Java Reflection Tutorial

Hi all, this is my second post in 2015. Here in this tutorial i am going to focus little bit on Java’s one of the powerful concept called “Reflection”.

What is reflection?


“Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine.” This concept is often mixed with introspection. Now let us see the definitions of “Reflection” & “Introspection”.

Introspection is the ability of a program to examine the type or properties of an object at runtime.
Reflection is the ability of a program to examine and modify the structure and behavior of an object at runtime.

Reflection

Let us see simple code snippets about the two concepts as below.
Introspection Example: The instanceof operator determines whether an object belongs to a particular class.

if(obj instanceof CoffeeBean){
   CoffeeBean cb = (CoffeeBean)obj;
   cb.startMakingCoffee();
}

Reflection Example: The Class.forName() method returns the Class object associated with the class/interface with the given name(a string and full qualified name). The forName method causes the class with the name to be initialized.

// with reflection
Class<?> c = Class.forName("com.spark.beverages.CoffeeBean");
Object cb = c.newInstance();
Method m = c.getDeclaredMethod("startMakingCoffee", new Class<?>[0]);
m.invoke(cb);

Most of the web frameworks make use of reflection to make changes to objects using “Reflection”, some of the practical examples are as follows.

For example, Spring makes use of bean configuration such as:

<bean id="beanID" class="com.spark.beverages.CoffeeBean>
    <property name="someField" value="someValue" />
</bean>

When the Spring context processes this element, it will use Class.forName(String) with the argument “com.spark.beverages.CoffeeBean” to instantiate that Class. It will then again use reflection to get the appropriate setter for the element and set its value to the specified value.

let us consider the Servlet web applications, the same explanation applies to servlet configuration files also

<servlet>
    <servlet-name>someServlet</servlet-name>
    <servlet-class>com.spark.beverages.CoffeeBeanServlet</servlet-class>
<servlet>

Now let us see some examples on how to make use of Reflection API in java. Please go through the code carefully and its very easy to understand. The below code explains how to call different methods with different parameters and different return types.

/**
 * 
 */
package com.spark.java8.reflection;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Sony
 *
 */
public class CoffeeBean {

	public void startMakingCoffee() {
		System.out.println("Coffee Making Started ...");
	}

	public void startMakingCoffee(String coffeeName) {
		System.out.println("Making of " + coffeeName + " Started ...");
	}

	public List<String> getBevarages() {
		List<String> list = new ArrayList<>(); // Using Java 7 feature
		list.add("Moka");
		list.add("caffuccino");
		list.add("Espressino");
		list.add("Black eye");
		list.add("Iced coffee");
		return list;
	}

	public int getTimeToMakeCoffee(String coffeeName) {
		if ("caffuccino".equalsIgnoreCase(coffeeName)) {
			return 15;
		} else {
			return 5;
		}
	}

}
/**
 * 
 */
package com.spark.java8.reflection.test;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @author Sony
 *
 */
public class ReflectionTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			Class<?> clazz = Class
					.forName("com.spark.java8.reflection.CoffeeBean");
			Object object = clazz.newInstance();
			Method method = clazz.getDeclaredMethod("startMakingCoffee", null);
			method.setAccessible(true);
			method.invoke(object, null);
			
			System.out.println("-----------------------------------------------");
			Method method2 = clazz.getDeclaredMethod("startMakingCoffee",
					new Class[] { String.class });
			method2.setAccessible(true);
			method2.invoke(object, "caffuccino");
			
			System.out.println("-----------------------------------------------");
			Method method3 = clazz.getDeclaredMethod("getBevarages", null);
			method3.setAccessible(true);
			List<?> name = (List<?>) method3.invoke(object, null);
			for (Object object2 : name) {
				System.out.println(object2);
			}
			
			System.out.println("-----------------------------------------------");
			Method method4 = clazz.getDeclaredMethod("getTimeToMakeCoffee", new Class[]{String.class});
			method4.setAccessible(true);
			String beverageName = "Cold coffee";
			int time = (int) method4.invoke(object, beverageName);
			System.out.println("time to make "+beverageName+" is "+time+" mins");
			
		}
		//Using Java 7 feature of Multiple Catch.
		catch (ClassNotFoundException | NoSuchMethodException
				| SecurityException | IllegalAccessException
				| IllegalArgumentException | InvocationTargetException
				| InstantiationException e) {
			e.printStackTrace();
		}
	}

}

Happy Reflections 🙂 Happy Coding 🙂

Advertisements

One thought on “Java Reflection Tutorial

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s