Introduction To Reflection In Java

Introduction

In this article we discuss reflection in Java.

Description

Reflection is the process of determining or modifying the behaviour of a class at runtime. Java provides a java.lang.Class class that contain many methods, that help in finding metadata and to change the runtime behaviour of a class.

What's the use?

It is mainly used in:

  • Integrated Development Environments (IDEs), for example Eclipse, MyEclipse, NetBeans etcetera.
  • Test Tolls
  • Debugger etcetera.

This class generally used to performs two tasks

  • they have method, that is used to find and changes the runtime behaviour of a class.
  • they provide methods, that get the metadata of a class at runtime.

Some Drawbacks of reflection

  1. Performance overhead
  2. Security Restrictions
  3. Exposure of Internals

Some commonly used public methods of the Class class

  1. String getName()
  2. static Class forName(String className) throws ClassNotFoundException
  3. Object newInstnce() throws InstantiationException, IllegealAccessException
  4. boolean isInterface()
  5. boolean isArray()
  6. boolean isPrimitive()
  7. Class getSuperclass()
  8. Field[] getDeclaredFields() throws SecurityException
  9. Method[] getDeclaredMethods() throws SecurityException
  10. Constructor[] getDeclaredConstrutors() throws SecurityException
  11. Method getDeclaredMethod(String name, Class[] parameterTypes) throws NoSuchMethodException, SecurityException

How to determine the Object of the class at runtime

  1. By using forName() method.
  2. By using getClass() method
  3. By using .class syntax

1. Use of the forName() method

Example

class Reflection {}

class Check

  {

    public static void main(String args[]) throws ClassNotFoundException

      {

        Class cls=Class.forName("Reflection");

        System.out.println(cls.getName());

      }

  }

Output

fig-1.jpg

2. By using the getClass() method

Example

class Reflection{}

class Check

  {

    void printName(Object ob)

      {

        Class cls=ob.getClass();

        System.out.println(cls.getName());

      }

    public static void main(String args[])

      {

        Reflection ref=new Reflection();

        Test tst=new Test();

        tst.printName(ref);

      }

}

Output

fig-2.jpg

3. By using the .class syntax

Example

class Check

  {

    public static void main(String args[])

      {

        Class cls1=Check.class;

        System.out.println(cls1.getName());

        Class cls=boolean.class;

        System.out.println(cls.getName());

      }

  }

Output

fig-3.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all