Signup/Sign In

Java Reflection API

Reflection means ability of a software to analyze itself. In Java, Reflection API provides facility to analyze and change runtime behavior of a class at runtime.

For example, using reflection at the runtime you can determine what method, field, constructor or modifers a class supports.

The java.lang.Class class provides methods that are used to get metadata and manipulate the run time behavior of a class.

The java.lang andjava.lang.reflect packages provide many classes for reflection and get metadata of a particular class.

One of the advantage of reflection API is, we can manipulate private members of the class too.

What is reflect package?

java.lang.reflect package encapsulates several important interfaces and classes. These classes and interface define methods which are used for reflection.

Some Important Classes of java.lang.reflect package

ClassWhat it does ?
Arrayallow you to dynamically create and manipulate arrays
Constructorgives information about constructor of a class
Fieldprovide information about field
Methodprovide information about method
Modifierprovide information about class and member access modifier
Proxysupports dynamic proxy classes

Apart from these classes java.lang.Class is another very important class used in Reflection API.

Uses of Reflection

  • Developing IDE
  • Debugging and Test tools
  • Loading drivers and providing dynamic information

Disadvantages of Reflection

  • Low performance
  • Security risk
  • Violation of Oops concept

Java Class class

Java provides a class Class that contains methods to get the metadata of a class and manipulate the run time behavior of a class.

To perform reflection operation, we must use java.lang.Class that has public constructors for creating object.

Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader.

Java Class Methods

MethodDescription
public String getName()returns the class name
public static Class forName(String className)throws ClassNotFoundExceptionloads the class and returns the reference of Class class.
public Object newInstance()throws InstantiationException,IllegalAccessException creates new instance.
public boolean isInterface() checks if it is interface.
public boolean isArray() checks if it is array.
public boolean isPrimitive() checks if it is primitive.
public Class getSuperclass() returns the superclass class reference.
public Field[] getDeclaredFields()throws SecurityException returns the total number of fields of this class.
public Method[] getDeclaredMethods()throws SecurityException returns the total number of methods of this class.
public Constructor[] getDeclaredConstructors()throws SecurityException returns the total number of constructors of this class.
public Method getDeclaredMethod(String name,Class[] parameterTypes)throws NoSuchMethodException,SecurityException returns the method class instance.
public Class<?>[] getClasses() the array the array of Class objects representing the public members of this classof Class objects representing the public members of this class
public Field[] getFields() throws SecurityException the array of Field objects representing the public fields
public Method[] getMethods()throws SecurityException the array of Method objects representing the public methods of this class
public Constructor<?>[] getConstructors() throws SecurityException the array of Constructor objects representing the public constructors of this class
public Method getMethod(String name, Class<?>... parameterTypes) the Method object that matches the specified name and parameterTypes

How to retrieve Object of class ?

We can get object of a class using Class class. there are manly three ways that are listed below:

  1. Object.getClass()
  2. Using .class syntax
  3. Class.forName()

1. If we have instance of a class then we can get its qualified name using the getClass() method. This method is defined in Object class.

Lets take an example, where we are getting class name using the getclass method. The instance can be any custom or built-in class.

	
class Employee{
	int empId;
	String name;
}
class Demo{
	public static void main(String[] args) throws ClassNotFoundException {
		Employee employee = new Employee();
		// employee object
		Class name = employee.getClass();
		System.out.println(name);
		// string object
		name = "hello".getClass();
		System.out.println(name);
	}
}
	

class Employee class java.lang.String

2. If the type is available but there is no instance then it is possible to get a Class by using .class to the name of the type. This is also the easiest way to obtain the Class for a primitive type.

	
class Employee{
	int empId;
	String name;
}

class Demo{
	public static void main(String[] args) throws ClassNotFoundException {
		
		// Employee Type
		Class name = Employee.class;
		System.out.println(name);
		// string Type
		name = String.class;
		System.out.println(name);
	}
}
	

class Employee class java.lang.String

3. If we have fully-qualified name of a class, we can get the corresponding Class using the static method Class.forName(). This method cannot be used for primitive types. See the below example.

	
class Employee{
	int empId;
	String name;
}

class Demo{
	public static void main(String[] args) throws ClassNotFoundException {
		
		// Employee class
		Class name = Class.forName("Employee");
		System.out.println(name);
		// String class
		name = Class.forName("java.lang.String");
		System.out.println(name);
	}
}
	

class Employee class java.lang.String

In our next topic, we will discuss to get metadata of a class, method, fields etc.