Java Reflection

  • Reflection is the key to Java being seen as a dynamic language. Reflection allows programs to use the Reflection API to retrieve internal information about any class (–> class, class name, class interface, class methods, class fields, class properties, etc.) during execution. And can directly operate any object’s internal properties and methods.

    Class c = Class.forName(“java.lang.String”)

  • After the Class is loaded, an object of type Class (one Class object per Class) is generated in the method area of heap memory, which contains the complete structure information of the Class. We can see the structure of the class through this object. This object is like a mirror through which you can see the structure of the class, so we call it a reflection

Normal mode: import the required package class name –> Instantiate by New –> Get the instantiated object

Reflection: Instantiate the object ->getClass() method ->get the full package class name

Functionality provided by the Java reflection mechanism

  • Determine the class to which any object belongs at run time

  • Constructs an object of any class at run time

  • Determine which member variables and methods any class has at run time

  • Get generic information at run time

  • Call the member variables and methods of any object at run time

  • Handle the interpretation at run time

  • Generating dynamic proxies

  • .

Advantages and disadvantages of Java reflection

Advantages:

  • Dynamic object creation and compilation can be achieved, reflecting a great deal of flexibility.

Disadvantages:

  • Using reflection is basically an interpretation operation where we can tell the JVM what we want to do and it meets our requirements. This type of operation is always slower than performing the same operation directly.