AddThis Social Bookmark Button

Reflection:

  • In object oriented programming languages such as Java, reflection allows inspection of classes, interfaces, fields and methods at run-time without knowing the names of the interfaces, fields, methods at compile time
  • Reflection can be used for observing and/or modifying program execution at runtime
  • It also allows instantiation of new objects and invocation of methods
  • Reflection can also be used to adapt a given program to different situations dynamically

We need reflection for :

  1. Construct an object for a class at runtime
  2. To examine a class’s field and method at runtime
  3. Invoke any method of an object at runtime without knowing name.
  4. For examine an object’s class at runtime
  5. To change accessibility flag of Constructor, Method and Field


Example 1

 By using reflection write  the code, which will find out  method called "printHelloWorld"(if present in  that class) and then call it.

//ReflectionHelloWorld.java contains printHelloWorld method

package com.reflection;

public class ReflectionHelloWorld {

	String hello="Hello World Reflection";
	public void printHelloWorld(){
		System.out.println(hello);
	}

}

We use ReflectionTest.java to call the above method using Reflection

package com.reflection;

import java.lang.reflect.Method;

public class ReflectionTest {

	
	public static void main(String[] args) {
			
		
		ReflectionHelloWorld helloWorld= new ReflectionHelloWorld();
		Method method;
		try{
			method=helloWorld.getClass().getMethod("printHelloWorld", new Class<?>[0]);
			method.invoke(helloWorld);
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}

}

O/P

Hello World Reflection

Example 2

This Example says how to create object from Class Instance .

ReflectionHelloWorld.java
package com.reflection;
public class ReflectionHelloWorld {

	String hello="Hello World Reflection";
	public void printHelloWorld(){
		System.out.println(hello);
	}
} 

 ReflectionTest1.java

package com.reflection;

public class ReflectionTest1 {

	
	public static void main(String[] args) {
		// instance of "Class"
				Class<?> c = null;
				try{
					c=Class.forName("com.reflection.ReflectionHelloWorld");
				}catch(Exception e){
					e.printStackTrace();
				}
		 
				// instance of "ReflectionHelloWorld"
				ReflectionHelloWorld hello = null;
		 
				try {
					hello = (ReflectionHelloWorld) c.newInstance();
				} catch (Exception e) {
					e.printStackTrace();
				}	
		 
				hello.printHelloWorld();
	}
}

Class.forName is used to instantiate class dynamically.

O/P

Hello World Reflection

Example 3

Instantiate By Constructor

This example show how to instantiate a class by constructor(Default and Argumented)

ReflectionWorld.java contains default and argument constructor .

package com.reflection;

public class ReflectionWorld {

	String hello;
	public void printHelloWorld(){
		System.out.println(hello);
	}
	public ReflectionWorld() {
		System.out.println("Default constructor loaded");
	}
	public ReflectionWorld(String str) {
		this.hello=str;
		System.out.println(hello);
	}
}

ReflectionTestByConstructor.java is used to instantiate ReflectionWorld Class to instantiate by constuctor
package com.reflection;

import java.lang.reflect.Constructor;

public class ReflectionTestByConstructor {

	public static void main(String[] args) {
		// instance of "Class"
		Class<?> c = null;
		try{
			c=Class.forName("com.reflection.ReflectionWorld");
		}catch(Exception e){
			e.printStackTrace();
		}

		// instance of "ReflectionHelloWorld"
		ReflectionWorld hello1 = null;
		ReflectionWorld hello2 = null;
		Constructor<?> cons[] = c.getConstructors();
		try {
			hello1 =  (ReflectionWorld)cons[0].newInstance();
			hello2 =  (ReflectionWorld)cons[1].newInstance("Hello World");
		} catch (Exception e) {
			e.printStackTrace();
		}	
		hello1.printHelloWorld();
		hello2.printHelloWorld();

	}

}

O/P

Default constructor loaded

Hello World

null

Hello World

Example 4

 Access a field's value in an object using reflection

This example shows how to access private field     of a class using reflection .

Person.java

package com.reflection;
public class Person {
	private final String name;
	private final String add;
	private final String zipCode;
	public Person(String name, String add, String zipCode) {
		super();
		this.name = name;
		this.add = add;
		this.zipCode = zipCode;
	}


}

In TestField.java java , we are accessing private field of  Person

package com.reflection;
import java.lang.reflect.Field;
public class TestFields {
	 public void reflectionTest() throws Exception {
		    Person person = new Person("Aled", "USA", "00976");
		    Field[] fields = person.getClass().getDeclaredFields();
		    for (Field field : fields) {
		    	
		    	field.setAccessible(true);
		      System.out.println("Field Name: " + field.getName());
		      System.out.println("Field Type: " + field.getType());
		      System.out.println("Field Value: " + field.get(person));
		      		    }
	 }
  public static void main(String args[]) throws Exception {
    new TestFields().reflectionTest();
  

  }
	 }

O/P

Field Name: name
Field Type: class java.lang.String
Field Value: Aled
Field Name: add
Field Type: class java.lang.String
Field Value: USA
Field Name: zipCode
Field Type: class java.lang.String
Field Value: 00976