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 🙂

Introduction to Arduino

Hi All these days i got more fascinated towards IoT (Internet Of Things) the hot topic in market research, so i thought of doing research myself and started digging into it, then i came across may one of the hardware boards of which i was attracted to “Arduino”. When i told about Arduino to my friends the very first question i got from them is “What is Arduino ?” and “Why only Arduino ?” so i wanted to answer them infact Arduino corporation have answered the question in their site(Credits to arduino.cc)

What is Arduino?

Arduino is a tool for making computers that can sense and control more of the physical world than your desktop computer. It’s an open-source physical computing platform based on a simple microcontroller board, and a development environment for writing software for the board.

Arduino can be used to develop interactive objects, taking inputs from a variety of switches or sensors, and controlling a variety of lights, motors, and other physical outputs. Arduino projects can be stand-alone, or they can communicate with software running on your computer (e.g. Flash, Processing, MaxMSP.) The boards can be assembled by hand or purchased preassembled; the open-source IDE can be downloaded for free.

The Arduino programming language is an implementation of Wiring, a similar physical computing platform, which is based on the Processing multimedia programming environment.

Why Arduino?

There are many other microcontrollers and microcontroller platforms available for physical computing. Parallax Basic Stamp, Netmedia’s BX-24, Phidgets, MIT’s Handyboard, and many others offer similar functionality. All of these tools take the messy details of microcontroller programming and wrap it up in an easy-to-use package. Arduino also simplifies the process of working with microcontrollers, but it offers some advantage for teachers, students, and interested amateurs over other systems:

Inexpensive – Arduino boards are relatively inexpensive compared to other microcontroller platforms. The least expensive version of the Arduino module can be assembled by hand, and even the pre-assembled Arduino modules cost less than $50
Cross-platform – The Arduino software runs on Windows, Macintosh OSX, and Linux operating systems. Most microcontroller systems are limited to Windows.
Simple, clear programming environment – The Arduino programming environment is easy-to-use for beginners, yet flexible enough for advanced users to take advantage of as well. For teachers, it’s conveniently based on the Processing programming environment, so students learning to program in that environment will be familiar with the look and feel of Arduino
Open source and extensible software- The Arduino software is published as open source tools, available for extension by experienced programmers. The language can be expanded through C++ libraries, and people wanting to understand the technical details can make the leap from Arduino to the AVR C programming language on which it’s based. Similarly, you can add AVR-C code directly into your Arduino programs if you want to.
Open source and extensible hardware – The Arduino is based on Atmel’s ATMEGA8 and ATMEGA168 microcontrollers. The plans for the modules are published under a Creative Commons license, so experienced circuit designers can make their own version of the module, extending it and improving it. Even relatively inexperienced users can build the breadboard version of the module in order to understand how it works and save money.

Happy IoT, Happy Arduino 🙂