Table of contents
1.
Introduction
2.
Definition
3.
Uses of Reflection API
4.
The Reflect Package
5.
Java 'Class' Class
6.
Getting the Complete Information About the Class
6.1.
Using forName() Method
6.1.1.
Code
6.1.2.
Output
6.2.
Using getClass() Method
6.2.1.
Code
6.2.2.
Output
6.3.
Using .class Syntax
6.3.1.
Code
6.3.2.
Output
7.
Determining the Class Object
7.1.
Code
7.2.
Output
8.
Getting the Metadata of a Class
8.1.
Code
8.2.
Output
9.
Getting the Metadata of a Variable
9.1.
Code
9.2.
Output
10.
Getting the Metadata of a Method
10.1.
Code
10.2.
Output
11.
Getting the Metadata of a Constructor
11.1.
Code
11.2.
Output
12.
Advantages & Disadvantages
13.
Frequently Asked Questions
14.
Conclusion
Last Updated: Mar 27, 2024

Reflection API in Java

Author Aniket Majhi
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Welcome readers! I hope that you are doing well.
In this era, programming is an essential part of the programmers like you guys. Day by day, the number of programmers is increasing. So if you want to stand out from the crowd or if you want to make an impression, you have to put in some extra effort.
This article will discuss such a concept, namely the Reflection API in Java. Here, you will learn a completely clear-cut concept about the Reflection API, which will help you enhance your Java knowledge.

So, without further ado, let’s start the topic.

Definition

The Java reflection is the process of examining and changing the runtime behaviour of a class at runtime.

It manipulates the class and its members(fields, constructor, methods) at runtime. The main advantage of the Java reflection API is that it can also manipulate the private members of the classes.

The java.lang.reflect package in Java provides many methods to implement reflection in Java.

The java.lang.Class class provides different methods to get the metadata, change and examine the behaviour at runtime.

Uses of Reflection API

The Java reflection API is mainly used in

  1. Developing IDE
  2. Debugging
  3. Testing tools
  4. Loading drivers
  5. 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.

  1. 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.
  2. 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.
  3. Method: This class provides information about a method such as access modifiers, return type, name, parameter type and exception type.
  4. 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.

  1. public String getName(): This method returns the name of the class.
  2. public Class getSuperClass(): This method returns the superclass reference.
  3. public Class[] getInterfaces(): This method returns an array of interfaces implemented by the specified class.
  4. 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)”.
  5. public static Class forName(String className) throws ClassNotFoundException: This method loads the class and returns the reference of the Class class.
  6. public boolean isInterface(): It checks if it is an interface.
  7. public boolean isArray(): It checks if it is an array.
  8. 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

  1. 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.
     
  2. What are the limitations of the Java reflection?
    The limitations of the Java reflection include the low performance of its operation, security risk etc.
     
  3. 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.
     
  4. 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 classvariablemethodconstructor.

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 JavaHow 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!

Live masterclass