Reflection in Java with example

In this post, we will see what is a reflection in java with example and what are the benefits. Also, we will see how to use reflection in a real-time scenario.

Reflection in java.

Reflection is a way to change the behavior of a class at runtime using different predefined API.

Benefits of Reflection in Java.

  • We can get information about class members(fields, constructors and methods) using reflection API(see examples).
  • We can access private members using reflection(see examples).
  • We can define our framework/custom utility methods using reflection, which can be used later in our development.
  • Sometimes reflection also useful to write JUnit for private methods(see examples).
  • To IDE development like an eclipse, IntelliJ, STS.

Disadvantage of reflection in Java.

  • While using reflection it may result as a performance issue.
  • We can access private fields outside of class. We are breaking encapsulation.

Some predefined API which frequently used in Reflection mechanism.

  • Class – This is a final class available in java.lang package.
  • Method – This is a final class which is available in java.lang.reflect package.
  • Field – This is also a class final which is available in java.lang.reflect package.
  • Constructor – This is also a final class available in java.lang.reflect package.
  • Annotation – This is an interface available in java.lang.annotation package.

Class class example using reflection in java.

Let’s see some example related to Class.

Example 1 – Get the Class class object and calling their methods using java reflection.

package refection1;

class ClassExample1 {

	public static void main(String[] args) throws ClassNotFoundException {

		// get Class object
		Class classObj = Class.forName("refection1.ClassExample1");

		// It will return super class name
		System.out.println("Super class of class name     " + classObj.getSuperclass());

		// it will return fully qualified class name
		System.out.println("Fully qualified class name is " + classObj.getName());

		// It will return class name without package
		System.out.println("class name without package    " + classObj.getSimpleName());

		// We can get class loader name
		System.out.println("Class loader name is          " + classObj.getClassLoader());
		
		// This will return package name
		System.out.println("package name is               " + classObj.getPackage());

	}
}

Output is –

Super class of class name class java.lang.Object
Fully qualified class name is refection1.ClassExample1
class name without package ClassExample1
Class loader name is sun.misc.Launcher$AppClassLoader@73d16e93
package name is package refection1

Example 2 – In this example, we will get constructors details using reflection java.

package refection1;

import java.lang.reflect.Constructor;

import com.sun.xml.internal.bind.v2.runtime.reflect.opt.Const;

public class Example2 {

	public Example2() {

	}

	public Example2(String name) {

	}

	public static void main(String[] args) throws ClassNotFoundException {

		// get Class object
		Class classObj = Class.forName("refection1.Example2");

		// get all defined constructor as of we have two.
		Constructor[] constructorArray = classObj.getConstructors();

		System.out.println(" First Constructor  is -- " + constructorArray[0]);
		System.out.println(" Second Constructor is -- " + constructorArray[1]);

	}
}

Output is –

First Constructor is — public refection1.Example2()
Second Constructor is — public refection1.Example2(java.lang.String)

Note – The method getConstructors() only return list of constructor which is public. If you use any other modifier than public, it will return an empty array. Let’s see an example.

Example 3 –

package refection1;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

import com.sun.xml.internal.bind.v2.runtime.reflect.opt.Const;

public class Example2 {

	Example2() {

	}

	Example2(String name) {

	}

	public static void main(String[] args) throws ClassNotFoundException {

		// get Class object
		Class classObj = Class.forName("refection1.Example2");

		// get all defined constructor as of we have two.
		Constructor[] constructorArray = classObj.getConstructors();

		System.out.println(constructorArray.length);

	}
}

Output is – 0

If we will try to access the element from constructorArray we will get java.lang.ArrayIndexOutOfBoundsException.

Note – We can access even other constructors( including private) using reflection, using method setAccesible(true), We will see later in example.

Example 4 – In this example, we will get all the methods and fields using reflection APIs getDeclaredMethods() and getDeclaredFields() methods.

package refection1;


import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Example4 {
	
	private String name;
	
	private int a;
	
	public void m1() {

	}

	public void m2() {

	}

	private void m3() {

	}
	
	

	public static void main(String[] args) throws ClassNotFoundException {

		// get Class object
		Class classObj = Class.forName("refection1.Example4");

		// get all defined methods as of now we have three(m1(), m2() and m3()).
		Method[] methodArr = classObj.getDeclaredMethods();

		for(Method method : methodArr) {
			System.out.println(method.toString());
		}
		
		System.out.println("-----fields inside class Example4-----");
		// get all defined fields.
		Field[] fieldArr = classObj.getDeclaredFields();

		for(Field field : fieldArr) {
			System.out.println(field.toString());
		}		
	}
}

Output is –

public static void refection1.Example4.main(java.lang.String[]) throws java.lang.ClassNotFoundException
public void refection1.Example4.m1()
public void refection1.Example4.m2()
private void refection1.Example4.m3()
—–fields inside class Example4—–
private java.lang.String refection1.Example4.name
private int refection1.Example4.a

Method class example using Java Reflection.

Example 1 –

package refection1;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class Example5 {

	public void m1() {

	}

	public static void main(String[] args) throws ClassNotFoundException {

		// get Class object
		Class classObj = Class.forName("refection1.Example5");

		// get all methods
		Method[] methodsArr = classObj.getDeclaredMethods();

		System.out.println("-----get parameter count----");
		for (Method method : methodsArr) {
			System.out.println(method.getParameterCount());
		}

		System.out.println("-----get the method name----");
		for (Method method : methodsArr) {
			System.out.println(method.getName());

		}

		System.out.println("--get the method return type--");
		for (Method method : methodsArr) {
			System.out.println(method.getReturnType());

		}

	}
}

output is –

—–get parameter count—-
1
0
—–get the method name—-
main
m1
–get the method return type–
void
void

Field class example using Reflection.

Example –

package refection1;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Example5 {

	String name = "ram";
	int a = 0;

	public static void main(String[] args) throws ClassNotFoundException, IllegalArgumentException, IllegalAccessException {

		// get Class object
		Class classObj = Class.forName("refection1.Example5");

		// get all field defined in Example5 class
		Field[] fieldArr = classObj.getDeclaredFields();

		System.out.println("-----get filed name----");
		for (Field field : fieldArr) {
			System.out.println(field.getName());
		}
		
		System.out.println("-----get field type name----");
		for (Field field : fieldArr) {
			System.out.println(field.getGenericType());
		}

		

	}
}

Output is –

—–get filed name—-
name
a
—–get field type name—-
class java.lang.String
int

Reflection in java – Consctructor class example.

package refection1;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

public class Example6 {
	public static void main(String[] args) throws ClassNotFoundException {
		// get Class object
		Class classObj = Class.forName("refection1.Example6");

		// get all constructors
		Constructor[] constArr = classObj.getDeclaredConstructors();

		System.out.println("-----get constructor name----");
		for (Constructor constr : constArr) {
			System.out.println(constr.toGenericString());
		}

	}
}

Output is –

—–get constructor name—-
public refection1.Example6()

So far we have seen the basics of some classes and methods used in java reflection. Let’s see how to access private members(field, methods, and constructors) outside of any class using the reflection mechanism. Suppose we have some java beans class where we have defined private variables. Generally, we can access these private variables only using getter and setter. Same way if have private methods and constructors we cannot access outside of any class. Let’s see a couple of examples where we will access private members outside of that class using java reflection.

Accessing private variable outside of class – We have two classes Employee and Example1 in same package reflection1. In Employee class we have a private field private String name = “ram”.

Employee.java

package reflection1;

public class Employee {

	private String name = "ram";

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}


}

Example1.java

package reflection1;

import java.lang.reflect.Field;

public class Example1 {
	public static void main(String[] args) throws Exception{
		Employee emp = new Employee();
		// get Class object
		Class classObj = Class.forName("reflection1.Employee");

		// get all fields
		Field[] fieldArr = classObj.getDeclaredFields();
		
		for(Field field : fieldArr) {
			
			String fieldValue = (String) field.get(new Employee());
			System.out.println(fieldValue);
			
		}
		 

	}
}

Let’s run the Example1.java.

Output is –

Exception in thread “main” java.lang.IllegalAccessException: Class reflection1.Example1 can not access a member of class reflection1.Employee with modifiers “private”
at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(Unknown Source)
at java.lang.reflect.AccessibleObject.checkAccess(Unknown Source)
at java.lang.reflect.Field.get(Unknown Source)
at reflection1.Example1.main(Example1.java:16)

We are not able to access private variable outside the class. Let’s use method setAccessible(true).

package reflection1;

import java.lang.reflect.Field;

public class Example1 {
	public static void main(String[] args) throws Exception{
		Employee emp = new Employee();
		// get Class object
		Class classObj = Class.forName("reflection1.Employee");

		// get all fields
		Field[] fieldArr = classObj.getDeclaredFields();
		
		for(Field field : fieldArr) {
			
			field.setAccessible(true);
			String fieldValue = (String) field.get(new Employee());
			System.out.println("name is -- "+fieldValue);
			
		}
		 

	}
}

Output is –

name is — ram

Accessing private method outside of class –

Employee.java

package reflection1;

public class Employee {

	private String m1() {
		return "mohan";
	}

}

Example1.java

package reflection1;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Example1 {
	public static void main(String[] args) throws Exception{
		// get Class object
		Class classObj = Class.forName("reflection1.Employee");

		// get methods
		Method[] methodArr = classObj.getDeclaredMethods();
		
		for(Method methodObj : methodArr) {
			
			methodObj.setAccessible(true);
			String methodValue = (String) methodObj.invoke(new Employee(), null);
			System.out.println("name is -- " +methodValue);
			
		}
		
		
	}
}

Output is –

name is — mohan

Accessing private Constructor outside of class –

Employee.java

package reflection1;

public class Employee {

	private Employee() {
		System.out.println("i am a private constructor");
	}

}

Example1.java

package reflection1;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Example1 {
	public static void main(String[] args) throws Exception{
		// get Class object
		Class classObj = Class.forName("reflection1.Employee");

		// get all constructors defined in Example1 class
		Constructor [] constructorArray = classObj.getDeclaredConstructors();
		 

		for(Constructor constructor : constructorArray) {
			
			constructor.setAccessible(true);
			Employee empObj = (Employee) constructor.newInstance();
			
			
		}
	}
}

Output is –

i am a private constructor

That’s all about Reflection in Java with example.

You may like.

Other core java tutorial.

Java reflection docs.

Summary – we have seen Java Reflection with example.