Reflection in Java

Reflection in Java with Examples

In this article, I am going to discuss Reflection in Java with Examples. Please read our previous article where we discussed Parallel Programming in Java with Examples. At the end of this article, you will understand what is Reflection and How to use Reflection in Java with Examples.

What is Reflection in Java?

Reflection is the ability of software to research itself. This is often provided by the java.lang.reflect package and elements. Reflection is a crucial capability, especially when using components called Java Beans. It allows you to research a software component and describe its capabilities dynamically, at run time instead of at compile time. For instance, by using reflection, you’ll determine what methods, constructors, and fields a category supports. Reflection provides information about the category to which an object belongs and also the methods of that class which may be executed by using the thing. Through reflection, we will invoke methods at runtime regardless of the access specifier used with them.

Classes defined in java.lang.reflect
  1. Array: It allows us to dynamically create and manipulate arrays.
  2. Constructor: It provides us information about a constructor.
  3. Field: It provides us information about a field.
  4. Method: It provides us information about a method.
  5. Modifier: It provides us information about the class and member access modifiers.
  6. ReflectPermission: It allows us the reflection on private or protected members of a class.
Methods of java.lang.reflect
  1. getName(): It returns the name of the class.
  2. getSuperclass(): It returns the superclass reference
  3. getInterfaces(): It returns an array of interfaces implemented by the specified class
  4. getModifiers(): It returns an int containing flags that describe which modifiers apply for the given class.
  5. getDeclaredMethod(): It is used to create an object of the method to be invoked. 
  6. invoke(): It is used to invoke a method of the class at runtime.
  7. getDeclaredField(FieldName): It is used to get the private field. It returns an object of type Field for the specified field name.
  8. setAccessible(true): It allows us to access the field irrespective of the access modifier used with the field.
  9. newInstance(): It is used to create a new instance of the class. The newInstance() method of a Class class can invoke zero-argument constructor whereas the newInstance() method of Constructor class can invoke any number of arguments.
Example to demonstrate Reflection in Java

It prints the Class name, Constructors, Fields, Methods of the given class.

import java.lang.reflect.*;
public class ReflectionDemo1
{
    public static void main (String args[])
    {
        try
        {
            Class c = Class.forName ("java.awt.Dimension");
            System.out.println ("Class : " + c.getName ());
            System.out.println ("Constructors:");
            Constructor constructors[] = c.getConstructors ();
            for (int i = 0; i < constructors.length; i++)
            {
                System.out.println (" " + constructors[i]);
            }
      
            System.out.println ("Fields:");
            Field fields[] = c.getFields ();
            for (int i = 0; i < fields.length; i++)
            {
                System.out.println (" " + fields[i]);
            }
         
            System.out.println ("Methods:");
            Method methods[] = c.getMethods ();
            for (int i = 0; i < methods.length; i++)
            {
                System.out.println (" " + methods[i]);
            }
        } 
        catch (Exception e)
        {
            System.out.println ("Exception: " + e);
        }
    }
}
Output

Example to demonstrate Reflection in Java

Example to understand Reflection in Java
import java.lang.reflect.Method;
import java.lang.reflect.Field;
import java.lang.reflect.Constructor;

class Test
{
    private String s;

    public Test ()
    {
        s = "Java Relection API";
    }

    public void method1 ()
    {
        System.out.println ("String : " + s);
    }

    public void method2 (int n)
    {
        System.out.println ("Number : " + n);
    }

    private void method3 ()
    {
        System.out.println ("Private method invoked");
    }
}

class ReflectionDemo2
{
    public static void main (String args[]) throws Exception
    {
        Test obj = new Test ();

        Class cls = obj.getClass ();
        System.out.println ("Class : " + cls.getName ());

        Constructor constructor = cls.getConstructor ();
        System.out.println ("Constructors : " + constructor.getName ());

        System.out.println ("Methods : ");

        Method[] methods = cls.getMethods ();
        for (Method method:methods)
        {
            System.out.println (method.getName ());
        }

        Method methodcall1 = cls.getDeclaredMethod ("method2", int.class);
        methodcall1.invoke (obj, 19);

        Field field = cls.getDeclaredField ("s");
        field.setAccessible (true);
        field.set (obj, "JAVA");

        Method methodcall2 = cls.getDeclaredMethod ("method1");
        methodcall2.invoke (obj);

        Method methodcall3 = cls.getDeclaredMethod ("method3");
        methodcall3.setAccessible (true);
        methodcall3.invoke (obj);
    }
}
Output

Example to understand Reflection in Java

Example to obtain public methods of a class in Java using Reflection
import java.lang.reflect.*;
public class ReflectionDemo3
{
    public static void main (String args[])
    {
        try
        {
            Aa a = new Aa ();
            Class c = a.getClass ();
            System.out.println ("Public Methods:");
            Method methods[] = c.getDeclaredMethods ();
            for (int i = 0; i < methods.length; i++)
            {
                int modifiers = methods[i].getModifiers ();
                if (Modifier.isPublic (modifiers))
                {
                    System.out.println (" " + methods[i].getName ());
                }
            }
        }
        catch (Exception e)
        {
            System.out.println ("Exception: " + e);
        }
    }
}

class Aa
{
    public void a1 ()
    {
    }

    public void a2 ()
    {
    }

    protected void a3 ()
    {
    }

    private void a4 ()
    {
    }
}
Output

Example to obtain public methods of a class in Java using Reflection

Advantages of Reflection in Java
  1. Extensibility Features: An application may use external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.
  2. Class Browsers and Visual Development Environments: A class browser must be ready to enumerate the members of classes. Visual development environments can enjoy making use of type information available in reflection to assist the developer in writing the correct code.
  3. Debuggers and Test Tools: Debuggers got to be ready to examine private members in classes. Test harnesses can make use of reflection to systematically call a discoverable set of APIs defined on a category, to ensure a high level of code coverage during a test suite.
Disadvantages of Reflection in Java
  1. Performance Overhead: Certain Java virtual machine optimizations cannot be performed because reflection involves types that are dynamically resolved.
  2. Security Restrictions: When running under a security manager, reflection requires a runtime permission which may not be present. This is in a crucial consideration for code that has got to run during a restricted security context, like in an Applet.
  3. Exposure of Internals: The use of reflection can result in unexpected side-effects because reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, which can render code dysfunctional and should destroy portability. Reflective code breaks abstractions and thus may change behavior with upgrades of the platform.

In the next article, I am going to discuss Date-Time APIs in Java with Examples. Here, in this article, I try to explain Reflection in Java with Examples. I hope you enjoy this Reflection in Java with Examples article.

Leave a Reply

Your email address will not be published. Required fields are marked *