Reflection API

Reflection in Java involves the dynamic analysis and manipulation of a class's behavior during runtime.

The java.lang.Class class offers a variety of methods that enable the retrieval of metadata, inspection, and modification of the behavior of a class during runtime.

The packages java.lang and java.lang.reflect contain classes that support Java reflection.

Where it is used

The Reflection API is mainly used in:

  • IDE (Integrated Development Environment) e.g., Eclipse, MyEclipse, NetBeans etc.
  • Debugger
  • Test Tools etc.
  • How many ways can we get the instance of Class class?
  • How to create the javap tool?
  • How to create the appletviewer tool?
  • How to access the private method from outside the class?
  • java.lang.Class class

The primary functions of the java.lang.Class class include:

  • Offering functionalities to access the class's metadata during runtime.
  • Offering functionalities to inspect and modify the behavior of a class during runtime.
  • Commonly used methods of Class class:

Method Description
1) public String getName() returns the class name
2) public static Class forName(String className)throws ClassNotFoundException loads the class and returns the reference of Class class.
3) public Object newInstance()throws InstantiationException,IllegalAccessException creates new instance.
4) public boolean isInterface() checks if it is interface.
5) public boolean isArray() checks if it is array.
6) public boolean isPrimitive() checks if it is primitive.
7) public Class getSuperclass() returns the superclass class reference.
8) public Field[] getDeclaredFields()throws SecurityException returns the total number of fields of this class.
9) public Method[] getDeclaredMethods()throws SecurityException returns the total number of methods of this class.
10) public Constructor[] getDeclaredConstructors()throws SecurityException returns the total number of constructors of this class.
11) public Method getDeclaredMethod(String name,Class[] parameterTypes)throws NoSuchMethodException,SecurityException returns the method class instance.

How to get the object of Class class?

There are 3 ways to get the instance of Class class. They are as follows:

  • forName method of Class class
  • getClass method of Object class
  • the .class syntax
  • 1) forName method of Class class

  • is used to load the class dynamically.
  • returns the instance of Class class.
  • It should be used if you know the fully qualified name of class.This cannot be used for primitive types.

Let's see the simple example of forName method.

FileName: Test.java

Example

class Simple{}  
  
public class Test{  
 public static void main(String args[]) throws Exception {  
  Class c=Class.forName("Simple");  
  System.out.println(c.getName());  
 }  
}

Output:

Output

Simple

2) getClass method of Object class

The method returns the Class object instance. It is recommended for situations where the type is known. Additionally, it is compatible with primitive data types.

FileName: Test.java

Example

class Simple{}

class Test{
  void printName(Object obj){
  Class c=obj.getClass();  
  System.out.println(c.getName());
  }
  public static void main(String args[]){
   Simple s=new Simple();
 
   Test t=new Test();
   t.printName(s);
 }
}

Output:

Output

Simple

3) The .class syntax

In cases where a type exists without an instance, it is feasible to acquire a Class by adding ".class" to the type's name. This method is applicable even for primitive data types.

FileName: Test.java

Example

class Test{
  public static void main(String args[]){
   Class c = boolean.class; 
   System.out.println(c.getName());

   Class c2 = Test.class; 
   System.out.println(c2.getName());
 }
}

Output:

Output

boolean
       Test

Determining the class object

The Class class provides the following techniques for identifying the class object:

1) The method isInterface in Java is a public boolean method that is used to check whether the Class object being referenced represents an interface type.

2) The method isArray in Java is a public boolean method that checks whether the Class object being referred to represents an array class or not.

3) The method isPrimitive in Java is a public boolean that can be used to check whether a given Class object represents a primitive data type.

Let's explore a straightforward illustration of utilizing the reflection API to identify the type of an object.

FileName: Test.java

Example

class Simple{}
interface My{}

class Test{
 public static void main(String args[]){
  try{
   Class c=Class.forName("Simple");
   System.out.println(c.isInterface());
   
   Class c2=Class.forName("My");
   System.out.println(c2.isInterface());
  
  }catch(Exception e){System.out.println(e);}

 }
}

Output:

Output

false
 true

Pros and Cons of Reflection

Caution is advised when utilizing Java reflection. Despite its numerous benefits, there are drawbacks to consider as well. First, let's explore the advantages.

Advantages: Reflection allows for the examination of interfaces, classes, methods, and fields at runtime, without requiring their names during compilation. It enables the invocation of methods, creation of instances, or modification of field values using reflection. This functionality supports the development of Visual Development Environments and class browsers, aiding developers in writing accurate code.

Downsides: The utilization of reflection can violate the concepts of encapsulation by enabling access to the private fields and methods of a class. This could result in the exposure of crucial data to external entities, posing a significant risk. An instance of this could be manipulating the private members of a class to hold a null value, subsequently causing a NullReferenceException for another user of the class, leading to unexpected behavior.

Another drawback is the performance overhead. Due to the dynamic resolution of types in reflection, there is a lack of optimization by the JVM (Java Virtual Machine). As a result, operations executed using reflection tend to be slower.

Conclusion

Due to the drawbacks outlined above, it is typically recommended to steer clear of utilizing reflection. This is an advanced functionality that ought to be reserved for programmers or developers with a solid understanding of the fundamentals of the language. It is crucial to bear in mind that whenever reflection is employed, it compromises the security of the application.

Next Topics of Reflection API Tutorial

Input Required

This code uses input(). Please provide values below: