Java Reflection API

Java Reflection is a process of examining or modifying the run time behavior of a class at run time.

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.

The java.lang and java.lang.reflect packages provide classes for java reflection.

Where it is used

The Reflection API is mainly used in:

  1. IDE (Integrated Development Environment) e.g. Eclipse, MyEclipse, NetBeans etc.
  2. Debugger
  3. Test Tools etc.

java.lang.Class class

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

  1. provides methods to get the metadata of a class at run time.
  2. provides methods to examine and change the run time behavior of a class.

Commonly used methods of Class class:

Method Description
public String getName() returns the class name
public static Class forName(String className)throws ClassNotFoundException loads the class and returns the reference of Class class.
public Object newInstance()throws InstantiationException,IllegalAccessException creates new instance.
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.

How to get the object of Class class?

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

  1. forName() method of Class class
  2. getClass() method of Object class
  3. the .class syntax

1) forName() method of Class class

  1. is used to load the class dynamically.
  2. returns the instance of Class class.
  3. It should be used if you know the fully qualified name of class.This cannot be used for primitive types.

Flash Soon


getClass() method of Object class

Flash Soon


The .class syntax

Flash Soon



Determining the class object

  1. public boolean isInterface(): determines if the specified Class object represents an interface type.
  2. public boolean isArray(): determines if this Class object represents an array class.
  3. public boolean isPrimitive() determines if the specified Class object represents a primitive type.

Let's see the simple example of reflection api to determine the object type.

Flash Soon



Copyright 2017 Design& Development