The Wayback Machine - https://web.archive.org/web/20240726114918/https://www.geeksforgeeks.org/reflection-in-java/
Open In App

Reflection in Java

Last Updated : 30 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Reflection is an API that is used to examine or modify the behavior of methods, classes, and interfaces at runtime. The required classes for reflection are provided under java.lang.reflect package which is essential in order to understand reflection. So we are illustrating the package with visual aids to have a better understanding as follows: 

java.lang.reflect

  • Reflection gives us information about the class to which an object belongs and also the methods of that class that can be executed by using the object.
  • Through reflection, we can invoke methods at runtime irrespective of the access specifier used with them.

reflection

 Reflection can be used to get information about class, constructors, and methods as depicted below in tabular format as shown:

Class  The getClass() method is used to get the name of the class to which an object belongs.
Constructors The getConstructors() method is used to get the public constructors of the class to which an object belongs.
Methods The getMethods() method is used to get the public methods of the class to which an object belongs.

We can invoke a method through reflection if we know its name and parameter types. We use two methods for this purpose as described below before moving ahead as follows:

  1. getDeclaredMethod()
  2. invoke()

Method 1: getDeclaredMethod(): It creates an object of the method to be invoked. 

Syntax: The syntax for this method

Class.getDeclaredMethod(name, parametertype)

Parameters:

  • Name of a method whose object is to be created
  • An array of Class objects

Method 2: invoke(): It invokes a method of the class at runtime we use the following method.

Syntax: 

Method.invoke(Object, parameter)

Tip: If the method of the class doesn’t accept any parameter then null is passed as an argument.

Note: Through reflection, we can access the private variables and methods of a class with the help of its class object and invoke the method by using the object as discussed above. We use below two methods for this purpose.

Method 3: Class.getDeclaredField(FieldName): Used to get the private field. Returns an object of type Field for the specified field name. 

Method 4: Field.setAccessible(true): Allows to access the field irrespective of the access modifier used with the field.

Important observations Drawn From Reflection API

  • Extensibility Features: An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.
  • Debugging and testing tools: Debuggers use the property of reflection to examine private members of classes.
  • Performance Overhead: Reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code that are called frequently in performance-sensitive applications.
  • Exposure of Internals: Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.

Example 

prpravate

Output:

Image

Example with code:

package contains Employee class with constructors , setters and getters method

Java




package org.geeksforgeeks.write;
 
import java.io.*;
import java.util.*;
 
 
public class Emp{
  private int eid;
  private double esal;
  private String ename;
   
  enum Week{
    SUN,TUE,WED;
  }
   
  @interface MyAnno{}
   
  public int getEid(){
    return eid;
  }
  public void setEid(int eid,int num, char ch){
    this.eid = eid;
  }
   
  public double getEsal(){
    return esal;
  }
  public void setEsal(double esal,float data, String name){
    this.esal = esal;
  }
   
  public String getEname(){
    return ename;
  }
  public void setEname(String ename){
    this.ename = ename;
  }
   
  // constructor
  public Emp(int eid, double esal, String ename){
    super();
    this.eid = eid;
    this.esal = esal;
    this.ename = ename;
  }
  Emp(){
  }
  class A{
  }
  class B{
  }
}


//Main Method with implementation of constructor, methods and classes 

Java




package org.geeksforgeeks.write;
 
import java.lang.reflect.Method;
import java.lang.reflect.Constructor;
import java.lang.reflect.Parameter;
 
 
public class GFG {
 
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void main(String[] args) throws ClassNotFoundException {
        Class c = Class.forName("org.geeksforgeeks.write.Emp");
//        Constructor array
        Constructor[] constructors = c.getDeclaredConstructors();
         
        for(Constructor constructor : constructors) {
            System.out.println("Name of Constructor : "+constructor);
         
            System.out.println("Count of constructor parameter : "+constructor.getParameterCount());
             
            Parameter[] parameters = constructor.getParameters();
            for(Parameter parameter : parameters) {
                System.out.println("Constructor's parameter : "+parameter);
            }
            System.out.println();
        }
        System.out.println();
//          Method Array
          Method[] methods = c.getDeclaredMethods();
          System.out.println("Length of method : "+methods.length);
       
        for(Method method : methods){
            System.out.println("Method name: \t"+method);
            System.out.println("Method return type : \t"+method.getReturnType());
            System.out.println("Method parameter count: \t"+method.getParameterCount());
            System.out.println();
            Parameter[] parameters = method.getParameters();
            for(Parameter parameter : parameters) {
                System.out.println("Method's Parameter : "+parameter);
            }
            System.out.println();
        }
        System.out.println();
//        Annotations
        Class[] classes = c.getDeclaredClasses();
        for(Class class1 : classes) {
            System.out.println("class: "+class1);
            System.out.println("Name of class: "+class1.getName());
        }
//        Annotations
        Annotation[] anno = c.getDeclaredAnnotations();
        for(Annotation annotation : anno) {
            System.out.println("Annotation: "+annotation);
        }
         
    }
 
}


Output:

Name of Constructor : public org.geeksforgeeks.write.Emp(int,double,java.lang.String)
Count of constructor parameter : 3
Constructor’s parameter : int arg0
Constructor’s parameter : double arg1
Constructor’s parameter : java.lang.String arg2

Name of Constructor : org.geeksforgeeks.write.Emp()
Count of constructor parameter : 0

Length of method : 6
Method name:  public int org.geeksforgeeks.write.Emp.getEid()
Method return type :  int
Method parameter count:  0

Method name:  public void org.geeksforgeeks.write.Emp.setEid(int,int,char)
Method return type :  void
Method parameter count:  3

Method’s Parameter : int arg0
Method’s Parameter : int arg1
Method’s Parameter : char arg2

Method name:  public double org.geeksforgeeks.write.Emp.getEsal()
Method return type :  double
Method parameter count:  0

Method name:  public void org.geeksforgeeks.write.Emp.setEsal(double,float,java.lang.String)
Method return type :  void
Method parameter count:  3

Method’s Parameter : double arg0
Method’s Parameter : float arg1
Method’s Parameter : java.lang.String arg2

Method name:  public java.lang.String org.geeksforgeeks.write.Emp.getEname()
Method return type :  class java.lang.String
Method parameter count:  0

Method name:  public void org.geeksforgeeks.write.Emp.setEname(java.lang.String)
Method return type :  void
Method parameter count:  1

Method’s Parameter : java.lang.String arg0

class: class org.geeksforgeeks.write.Emp$A
Name of class: org.geeksforgeeks.write.Emp$A
class: class org.geeksforgeeks.write.Emp$B
Name of class: org.geeksforgeeks.write.Emp$B
class: interface org.geeksforgeeks.write.Emp$MyAnno
Name of class: org.geeksforgeeks.write.Emp$MyAnno
class: class org.geeksforgeeks.write.Emp$Week
Name of class: org.geeksforgeeks.write.Emp$Week
 



Similar Reads

How to Invoke Method by Name in Java Dynamically Using Reflection?
Java Reflection API provides us information about a Class to which the Object belongs to including the methods in this class. Using these Reflection API we would be able to get invoking pointer for a method in a class with its name. There are two functions used for this purpose: Invoking method with its nameFinding a method by Name in a class and i
4 min read
How to call private method from another class in Java with help of Reflection API?
We can call the private method of a class from another class in Java (which is defined using the private access modifier in Java). We can do this by changing the runtime behavior of the class by using some predefined methods of Java. For accessing private methods of different classes we will use Reflection API. To call the private method, we will u
3 min read
Reflection Array Class in Java
The Array class in java.lang.reflect package is a part of the Java Reflection. This class provides static methods to create and access Java arrays dynamically. It is a final class, which means it can't be instantiated or changed. Only the methods of this class can be used by the class name itself. The java.util.Arrays class contains various methods
7 min read
How to prevent Singleton Pattern from Reflection, Serialization and Cloning?
Prerequisite: Singleton Pattern In this article, we will see what various concepts can break the singleton property of a class and how to avoid them. There are mainly 3 concepts that can break the singleton property of a class. Let's discuss them one by one. Reflection: Reflection can be caused to destroy singleton property of the singleton class,
6 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStream Class : defaultReadObject() : java.io.ObjectInpu
6 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.StrictMath class in Java | Set 2
Java.lang.StrictMath Class in Java | Set 1More methods of java.lang.StrictMath class 13. exp() : java.lang.StrictMath.exp(double arg) method returns the Euler’s number raised to the power of double argument. Important cases: Result is NaN, if argument is NaN.Result is +ve infinity, if the argument is +ve infinity.Result is +ve zero, if argument is
6 min read
java.lang.instrument.ClassDefinition Class in Java
This class is used to bind together the supplied class and class file bytes in a single ClassDefinition object. These class provide methods to extract information about the type of class and class file bytes of an object. This class is a subclass of java.lang.Object class. Class declaration: public final class ClassDefinition extends ObjectConstruc
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg