1. Type Detection Through Java Reflection
Reflection in Java is an approach of RTTI (Run Time Type Identification) in terms of C++ language. In addition, Java allows invoking the type members also. For example, once we find the type at Run-time we can also access its members.
One may think how we do not know a type at compile time. But in reality when we write code there are significant circumstances where we may not know the instance type. The Polymorphism is one good example in which we may not know the instance type at compile time. Through RTTI technique, we can identify it at Run-time on the fly. Reflection in Java helps in designing robust and configurable applications.
In this example, we will create two classes and one Interface. Then we will get its type name at Run-time.
2. What is Java class, Class and Instance?
A class in Java is a template definition of an object. Based on the class template one can create one or more objects. We call these objects as Instances.
A Class (Note the capital C) in Java is an in-built class (Template definition) that defines object types. Application developers cannot create an instance from it. However, Java will create the instances of it when an object of any type is loaded into memory at run-time. For Example, when Java application creates a class instance called SecurityFile, then Java creates a class instance of Class to denote its type.
From the instance of an object of type Class, we can fetch run-time information of the class type. For each type, Java can load only one Class instance in memory and we can get the RTTI from it. For Example, even if user created ten objects of SecurityFile class, Java creates only one instance of the Class for the class type SecurityFile. This one object is enough to get the type information about the object SecurityFile.
OK. We will start our example and learn further while we proceed.
3. The IOrg Interface
A Type in Java can represent an Array, Enumeration, Interface, class instances etc,. Now, we will create an Interface of type IOrg. Below is the code that defines the IOrg interface:
1 2 3 4 5 6 |
//Sample01: Define IOrg Interface public interface IOrg { public int getTotalIncome(); public int getTotalExpense(); } |
4. The Organization class
Now, we define a class template called Organization. It has two private and two public data members. Besides, we keep two public functions in the class. Moreover, this class implements the IOrg interface which we defined in the previous section. The class template definition for the Organization is below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
//Sample 02: Define Organization class public class Organization implements IOrg { private int Total_Income; private int Total_Expense; public int Total_Employee; public String Org_Name; public int getTotalIncome() { return Total_Income; } public int getTotalExpense() { return Total_Expense; } } |
5. The Department Class – Child of Organization
After we set the Organization class, we derive the Department class from it. This is not a good idea as Department is not an organization. At the same time, an organization may have one or more departments. We derived the Department from Organization just to test the Java reflection. This class has two public members. The class is below:
1 2 3 4 5 6 |
//Sample 03: Define Department class public class Department extends Organization { public int DeptID; public String Location; } |
So for we defined the types IOrg, Organization and Department. We also established a relationship between them. Now let us see, how we can retrieve the types at run-time using Java Reflection. The below picture shows the relationship between the types:

6. Detecting Types Dynamically Using Java Reflection
We can get java types at run-time using three kinds of techniques offered by the Java Reflection. These are listed below:
- <TypeName>.class technique
- Class.forName() technique
- <objectRef>.getClass() technique
We will explore each option with an example by making use of types we created in the earlier sections.
When we want to write a generic function for dealing with RTTI, we may end-up in creating the parameters. Parameters require well-defined types and how do we pass Class types which is not known? We must use the Class <?> syntax for denoting such a parameter. For example, look at the code snippet below:
1 2 3 4 5 |
//Sample04: Get Class Name public static void PrintClassInfo(Class<?> ClassName) { System.out.println(ClassName.getSimpleName()); } |
Here, when defining the function, we kept the Generic form of the Class instance by using the Class<?> notation. Next, we make a call to the getSimpleName method to print the Type passed to the PrintClassInfo function.
6.1 Reflection by TypeName.class
When we know the Class Type and object reference is not available, we can use the TypeName.class syntax to retrieve the Class from the class type. Have a look at the below code snippet:
1 2 3 4 5 |
//Sample05: Get the Name from Types System.out.println("Print Class Name from Type"); PrintClassInfo(Organization.class); PrintClassInfo(IOrg.class); PrintClassInfo(Department.class); |
Here, we use the TypeName.class syntax to retrieve the Class skeleton of Organization, IOrg and Department. So, we can pass it to the PrintClassInfo function which we defined in the previous section. This technique is also useful to get Class template of primitive types.
6.2 Reflection by getClass
We can call getClass method when the object reference is available in the caller context. The call will return the Class template instance to the caller for performing any RTTI operation. Now, look at the code snippet below:
1 2 3 4 5 6 7 8 |
//Sample06: Let us Get the Name from Object System.out.println("Print Class Name from Object"); Organization org = new Organization(); Department dept = new Department(); Organization Org1 = new Department(); PrintClassInfo(org.getClass()); PrintClassInfo(dept.getClass()); PrintClassInfo(Org1.getClass()); |
In the above code, have a peek at the code snippet’s line number 3 and 5. Now, in line 3, we are setting up the Organization object and pointing that through the reference Org of a class type Organization. Then we are forming the Department object in like manner. But this time in place of referencing it through the Department reference, we point it through the Organization reference named Org1. The below depiction shows the reference and physical class instance it points:

In the above picture, the Organization reference Org points to Organization object. This is a clear case as the reference and exact object fits to the same type. Besides, the reference Org1 of type Organization is pointing to a Department instance. Object-Oriented languages allow this given that there is a true relationship exists between the objects. In our example, the Department class is derived from the Organization class. This means, the Organization is the base class for the Department. As a result, a base class reference Org1 can point to a derived class object of type Department.
The Java Reflection, rightly finds the class type as department even though we pass Org1 of type Organization to the PrintClassInfo function. This because the actual object pointed by Org1 reference is a Department object.
6.3 Java Reflection by Class.forName
Java Reflection can get Class of a class instance from a fully qualified class name and forName() method. For example, if we want to retrieve Class template instance of a Math class, we need a fully qualified name java.lang.Math not just Math. Now, look at the example below:
1 2 3 4 5 6 7 8 9 10 |
//Sample07: From forName System.out.println("Print Class Name from Fully" + "Qualified Name"); try { PrintClassInfo(Class.forName("Organization")); } catch(Exception Ex) { System.out.println(Ex.toString()); } |
In our example, since Organization class is part of the default package, we specify none of the package specification in the class name. Hence, we supply the Organization class name as a string. Also note, we formed the class string with no package specification dots. We use the try...catch block to safe guard the call to forName() method as it may go wrong.
7. Complete Code Example
IOrg.java
1 2 3 4 5 6 |
//Sample01: Define IOrg Interface public interface IOrg { public int getTotalIncome(); public int getTotalExpense(); } |
Organization.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
//Sample 02: Define Organization class public class Organization implements IOrg { private int Total_Income; private int Total_Expense; public int Total_Employee; public String Org_Name; public int getTotalIncome() { return Total_Income; } public int getTotalExpense() { return Total_Expense; } } |
Department.java
1 2 3 4 5 6 |
//Sample 03: Define Department class public class Department extends Organization { public int DeptID; public String Location; } |
Main.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
public class Main { //Sample04: Get Class Name public static void PrintClassInfo(Class<?> ClassName) { System.out.println(ClassName.getSimpleName()); } public static void main(String[] args) { //Sample05: Get the Name from Types System.out.println("Print Class Name from Type"); PrintClassInfo(Organization.class); PrintClassInfo(IOrg.class); PrintClassInfo(Department.class); //Sample06: Let us Get the Name from Object System.out.println("Print Class Name from Object"); Organization org = new Organization(); Department dept = new Department(); Organization Org1 = new Department(); PrintClassInfo(org.getClass()); PrintClassInfo(dept.getClass()); PrintClassInfo(Org1.getClass()); //Sample07: From forName System.out.println("Print Class Name from Fully" + "Qualified Name"); try { PrintClassInfo(Class.forName("Organization")); } catch(Exception Ex) { System.out.println(Ex.toString()); } } } |
- Java Logging Using LogManager and Logger
- Table Relation – One-to-One, One-to-Many, Many-to-Many Explained
Categories: Java
Tags: .class, .getClass, Class.forName