Uses of Reflection API
The Java reflection API is mainly used in
- Developing IDE
- Debugging
- Testing tools
- Loading drivers
- Providing dynamic information
The Reflect Package
The Java reflect package(java.lang.reflect) encapsulates several important interfaces and classes, which define some methods used for reflection.
Some important classes of the java.lang.reflect package are shown below.
- Field: This class is in java.lang.reflect provides information about the fields. It gathers some declarative information such as datatype, name, value and access modifiers of a variable.
- Constructor: This class gives information about a class constructor. It is mainly used to gather the access modifiers, names and type of the parameters in a constructor.
- Method: This class provides information about a method such as access modifiers, return type, name, parameter type and exception type.
- Modifier: This class provides information about the class and the member access modifiers.
Java 'Class' Class
The Java Class class mainly performs two important tasks:
- It provides some methods to get the metadata of a class at runtime.
- It provides some methods to inspect and change the runtime behaviour of the class.
The important methods of the Java Class class are shown below.
- public String getName(): This method returns the name of the class.
- public Class getSuperClass(): This method returns the superclass reference.
- public Class[] getInterfaces(): This method returns an array of interfaces implemented by the specified class.
- public int getModifiers(): This method returns an integer value representing the specified class's modifiers. If you want to get the access specifiers of the given class, then you need to pass this integer value to the method “public static String toString(int i)”.
- public static Class forName(String className) throws ClassNotFoundException: This method loads the class and returns the reference of the Class class.
- public boolean isInterface(): It checks if it is an interface.
- public boolean isArray(): It checks if it is an array.
- public boolean isPrimitive(): It checks if it is primitive.
Getting the Complete Information About the Class
We can get the complete information about a class in mainly three ways:
- Using forName() method.
- Using getClass() method.
- Using .class syntax.
Using forName() Method
The below code will show you how to get the complete information about a class using the forName() method.
Code
public class Main{
public static void main(String[] args) throws ClassNotFoundException{
Class x = Class.forName("Main");
System.out.println(x.getName());
}
}

You can also try this code with Online Java Compiler
Run Code
Output

Using getClass() Method
The below code will show you how to get the complete information about a class using the getClass() method.
Code
public class Main{
public static void main(String[] args) throws ClassNotFoundException{
Main obj = new Main();
Class x = obj.getClass();
System.out.println(x.getName());
}
}

You can also try this code with Online Java Compiler
Run Code
Output

Try it on Online Java Compiler.
Using .class Syntax
The below code will show you how to get the complete information about a class using the .class method.
Code
public class Main{
public static void main(String[] args) throws ClassNotFoundException{
Class x = Main.class;
System.out.println(x.getName());
}
}

You can also try this code with Online Java Compiler
Run Code
Output

Determining the Class Object
We can determine the class object in mainly three ways:
- Using isInterface() method.
- Using isArray() method.
- Using isPrimitive() method.
Code
class A{}
interface B{}
public class Main{
public static void main(String[] args) throws ClassNotFoundException{
Class c = Class.forName("A");
System.out.println(c.isInterface());
Class c2 = Class.forName("B");
System.out.println(c2.isInterface());
}
}

You can also try this code with Online Java Compiler
Run Code
Output

Getting the Metadata of a Class
The below code will show you how can you get the metadata of a class.
Code
import java.lang.reflect.Modifier;
class A{}
interface B{}
interface D{}
abstract class C extends A implements B,D{}
public class Main{
public static void main(String[] args) throws ClassNotFoundException{
Class a = C.class;
System.out.println("Name of the class is: " + a.getName());
System.out.println("Name of the superclass is: " + a.getSuperclass().getName());
Class[] lis = a.getInterfaces();
System.out.print("Implemented interfaces are: ");
for(Class i : lis) {
System.out.print(i.getName() + " ");
}
System.out.println();
int mod = a.getModifiers();
System.out.println("Access modifiers of the class are: " +Modifier.toString(mod));
}
}

You can also try this code with Online Java Compiler
Run Code
Output

Getting the Metadata of a Variable
The below code will show you how can you get the metadata of a variable.
Code
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
// Class C contains some variables
class C {
public static int var1 = 8608;
public static int var2 = 9371;
public static String str = "Hello";
}
public class Main {
public static void main(String[] args) throws IllegalAccessException,IllegalArgumentException{
// Creating the object of the class C
C ob = new C();
Class var = ob.getClass();
// get the metadata of all the fields of class C
Field[] field= var.getDeclaredFields();
// run a loop to print name of the variable,datatypes, access modifiers
for(Field f : field) {
System.out.println("Variable name : "+f.getName());
System.out.println("Datatype:"+f.getType());
int mod = f.getModifiers();
System.out.println("Access Modifiers: "+Modifier.toString(mod));
System.out.println("Value: " + f.get(f));
System.out.println();
}
}
}

You can also try this code with Online Java Compiler
Run Code
Output

Getting the Metadata of a Method
The below code will show you how to get the metadata of a method
Code
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
// Class C contains some methods
class C {
public void methhod1() throws IllegalAccessException{
System.out.println("Demo method1");;
}
public void method2(int a , int b) throws IllegalArgumentException{
System.out.println("Demo method2");
}
public void method2(int a , int b , String c){
System.out.println("Demo method3");
}
}
public class Main {
public static void main(String[] args) throws IllegalAccessException,IllegalArgumentException{
// Creating the object of the class C
C ob = new C();
Class var = ob.getClass();
// get the metadata of all the Methods of class C
Method[] method= var.getDeclaredMethods();
// run a loop to print name of the method,return types, access modifiers, parameters type and exceptions thrown by the method
for(Method m : method) {
System.out.println("Method name : "+m.getName());
System.out.println("Return type:"+m.getReturnType());
int mod = m.getModifiers();
System.out.println("Access Modifiers: "+Modifier.toString(mod));
System.out.println("Method parameters types: ");
Class[] params = m.getParameterTypes();
for(Class i: params) {
System.out.println(i.getName() + " ");
}
Class[] exceptions = m.getExceptionTypes();
System.out.println("Exception thrown by the method : ");
for(Class i : exceptions) {
System.out.println(i.getName() + " ");
}
System.out.println();
}
}
}

You can also try this code with Online Java Compiler
Run Code
Output

Also see, Hashcode Method in Java
Getting the Metadata of a Constructor
The below code will show you how we can get the metadata of a constructor
Code
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.rmi.RemoteException;
// Class C contains some Constructors
class C {
public C() throws IllegalAccessException{}
public C(int a) throws IllegalArgumentException{}
public C(int a , int b , String c) throws RemoteException{}
}
public class Main {
public static void main(String[] args) throws IllegalAccessException,IllegalArgumentException{
// Creating the object of the class C
C ob = new C();
Class var = ob.getClass();
// get the metadata of all the Constructors of class C
Constructor[] constructor= var.getDeclaredConstructors();
// run a loop to print name of the Constructor, constructor modifiers, parameters type and exceptions thrown by the Constructor
for(Constructor c : constructor) {
System.out.println("Constructor name : "+c.getName());
int mod = c.getModifiers();
System.out.println("Constructor Modifiers: "+Modifier.toString(mod));
System.out.println("Constructor parameters types: ");
// params stores the parameter types of the constructor
Class[] params = c.getParameterTypes();
for(Class i: params) {
System.out.println(i.getName() + " ");
}
// exception stores the exceptions thrown by the constructor
Class[] exceptions = c.getExceptionTypes();
System.out.println("Exception thrown by the Constructor : ");
for(Class i : exceptions) {
System.out.println(i.getName() + " ");
}
System.out.println();
}
}
}

You can also try this code with Online Java Compiler
Run Code
Output

Advantages & Disadvantages
The advantages and disadvantages of the Reflection API in java are discussed below:

Check out this article - Upcasting and Downcasting in Java, Duck Number in Java
Frequently Asked Questions
-
What is the importance of the Java reflection API?
The importance of the Java reflection API is that it allows you to examine or modify the runtime behaviour of a class at runtime.
-
What are the limitations of the Java reflection?
The limitations of the Java reflection include the low performance of its operation, security risk etc.
-
Can Java reflection API access the private fields of a class?
Yes, it can access the private fields of a class using the setAccessible(true) on the method or field object which you want to access.
-
What is the alternative to the Java reflection?
One alternative to the Java reflection is to generate a class file dynamically.
Conclusion
In this article, we have extensively discussed the Reflection API in Java.
We started with a basic introduction, then we discussed,
- Definition
- What are the uses?
- The reflet package.
- The java.lang.Class class.
- How to get the complete information about a class using different methods i.e. using forName(), using getClass() and using .class syntax.
- How to determine the class object using methods isInterface(), isArray(), isPrimitive().
- How to get the metadata of a class, variable, method, constructor.
We hope that this blog has helped you enhance your knowledge regarding the Reflection API in Java and if you would like to learn more, check out our articles on Reverse Array in Java, How to Sort List in Java. Do upvote our blog to help other ninjas grow.
Head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, and much more.!
Happy Reading!