Java Reflection API

Reflection api is basically used to examine or modify the runtime behavior of applications running in the Java virtual machine.
Using java reflection api we can get any information related to class , interface , enum at run time.

  We can also use reflection to instantiate an object, invoke its methods, change field values at run time.

  java.lang and java.lang.reflect package provide classes to perform reflection related operations.

  The java.lang.Class class provides many methods that can be used to get metadata, examine and change the run time behavior of a class.


Uses of Reflection API

The Reflection API is mainly used in:

  It is used to develop IDE (Integrated Development Environment) e.g. Eclipse, MyEclipse, NetBeans etc.

  Used in Debugger.

  Used to develop Testing Tool etc.

Drawbacks of Reflection

We should not use reflection in normal programming where we already have access to the classes and interfaces because of following drawbacks.

  Poor Performance since java reflection resolve the types dynamically, it involves processing like scanning the classpath to find the class to load, causing slow performance.

  Security Restrictions Reflection requires runtime permissions that might not be available for system running under security manager. This can cause you application to fail at runtime because of security manager.

  Security Issues Using reflection we can access part of code that we are not supposed to access, for example we can access private fields of a class and change itâ??s value. This can be a serious security threat and cause your application to behave abnormally.

java.lang.Class class

The java.lang.Class class performs mainly two tasks:

  provides methods to get the metadata of a class at run time.

  It provides methods to examine and change the run time behavior of a class.

Note : It has no public constructor.

Commonly used methods of Class class

Commonly used methods of Class class are :

Method Description
public String getName() returns the class name.
public static Class forName(String className)throws ClassNotFoundException oads 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.

How to get the object of Class class?

There are 3 ways to get the instance of Class class. They are as follows:

  forName() method of Class class

  getClass() method of Object class

  the .class syntax

1) forName() method of Class class

Where to use this method...

  forName() method is used to load any class dynamically at run time.

  forName() method returns object of Class class.

  It should be used if you know the fully qualified name of class.This cannot be used for primitive types.

Example of using forName() method:

class My {
	My() {
		System.out.println("Default Constructor");
	}
}

class Test {
	public static void main(String[] args) {
		try {
			Class c = Class.forName("My");
			//now print the information
			System.out.println("class Name is :" +c.getName());
			System.out.println("parent class name is :"+c.getSuperclass().getName());

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
class Name is :My
parent class name is :java.lang.Object

My class is loaded at run time using forName() method.

2) getClass() method of Object class

It returns the instance of Class class. It should be used if you know the type. Moreover, it can be used with primitives.

Example

class My {
	My() {
		System.out.println("Default Constructor");
	}
}

class Test {

	public void printName(Object ob) {
		Class c = ob.getClass();
		System.out.println("class Name is :" + c.getName());
		System.out.println("parent class name is :"
				+ c.getSuperclass().getName());

	}

	public static void main(String[] args) {
		try {
			Test t = new Test();
			My m = new My();
			t.printName(m);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
Default Constructor
class Name is :My
parent class name is :java.lang.Object

3) The .class syntax

If a type is available but there is no instance then it is possible to obtain a Class by appending ".class" to the name of the type.It can be used for primitive data type also.

Example

    class Test{  
      public static void main(String args[]){  
       Class c = boolean.class;   
       System.out.println(c.getName());  
      
       Class c2 = Test.class;   
       System.out.println(c2.getName());  
     }  
    }  
 boolean
 Test