Reflection in Java

Reflection in java is an API that examines or modifies the behavior of classes, methods, fields and interfaces during runtime. It is called reflection because of its ability to examine other code, or itself, within the same system. This can be done even when a particular class is inaccessible.


Let's say we have a requirement as shown below. Observe the class given:

Now we have been asked to call all methods of this class as per client requirement.

  1. Client 1 says I need order of calling methods like:
    i. m1,m2,m4,m3

  2. Client 2 says I need order of calling methods like:
    i. m4,m2,m4

  3. Client 3 says I need order of calling methods like:
    i. m1,m2,m3,m4

If you observe order of methods of every client, you’ll find that they’are all different. To fulfill the above given requirement, we will follow the steps given below :

Let’s say there are many clients and their requirements will be different. We will go on writing code as shown above EmployeeTest.java

This is not dynamic. Tomorrow, any addition of client causes our code to change. This is what we don't want to do. Hence, this coding practice is not good.

To solve this requirement we must use reflection. We will be able to solve the above given requirement at a later stage of this chapter once we understand reflection completely.


Next Requirement
We have an excel sheet below:

Roll No Student Student Phone No Remark
1733 Kiran 8888809416 Java by kiran
1738 Jayshree 9552343698 www.javabykiran.com

Now we want to insert data from the excel sheet to table Student as shown below:

excel sheet data for reflection example in java

To use core java logic for insertion easily with less optimized code, you must use reflection.


Important points to remember about Reflection:

  1. Java Reflection makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods, etc.

  2. We can create objects dynamically by using reflection

  3. We can create an object of a class having private constructors as well, from outside a class. Hence, we can instantiate class from outside. This is not possible by simply creating an object by using new operator.

    This chapter will explain the basics of Java Reflection including how to work with arrays, annotations, generics and dynamic proxies, and how to do dynamic class loading and reloading. It will also show you how to do more specific tasks, like reading all getter methods of a class, or accessing private fields and methods of a class.

    This chapter will also clear up some of the confusion out there about what Generics information is available at runtime. Some people claim that all Generics information is lost at runtime. This is not true.

  4. Package in which all reflection classes are existing :
    java.lang.reflect

  5. For reflection we must know class [Class] first.
    Class is class name in java and exists in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. In reflection we will deal with preexisting classes like Method, Field, and Constructor and so on.


Let's say we have simple class as shown below:


To use reflection we must first get object of Class class.
The example below shows two ways.

In this example we will get all the information about class B by using c and c1 reference variables by using methods of Class class.

  1. Above given is class B (every information means --> two constructors, two methods and one variable).

  2. Here we can see the complete class B but sometimes you only know class name not members of that class. Then we must go for reflection.

  3. To complete this we use the below methods of class Class [In the second step we have added some reflection code in existing class A].


i. To Fetch All methods use the class below:


ii. To Fetch All Variables in class B


iii. Getting and Setting Field Values
Once you have obtained a Field reference you can get and set its values using the Field.get() and Field.set()methods, like this: // to execute this add variables in class B

To access a private method you will need to call the Class.getDeclaredMethod(String name, Class[] parameterTypes) or Class.getDeclaredMethods() method.
The methods Class.getMethod(String name, Class[] parameterTypes) and Class.getMethods() methods only return public methods, so they won't work.
Here is a simple example of a class with a private method, and below that is the code to access that method via Java reflection.


This code example will print out the text "return Value = The Private Value", which is the value returned by the method getPrivateString () when invoked on the PrivateObject instance created at the beginning of the code sample.

Notice the use of the method PrivateObject.class.getDeclaredMethod ("privateString"). This method helps to call private method.

It only returns methods declared in that particular class, not methods declared in any superclasses.

Observe the line in bold too. By calling Method.setAcessible (true), you turn off the access checks for this particular Method instance for reflection calls only. Now you can access it even if it is private, protected or package scope, even if the caller is not a part of those scopes. You can't access the method using normal code. The compiler won't allow it.

Dynamic class loading is a very helpful feature in java that lets us load java code which we are unaware of before the starting of a program. It is invoked at runtime.

Use Class.forName in this case.


In this example we see that the single method we used to get a class object. If we do not use this way we need to hard code like:

A a =new A(); // can't be changed later // we must know class name

Employee employee =new Employee (); // can't be changed later // we must know class name.

If somebody asks why we use class.forname, the answer will be dynamic class object creation.