Reflection in Java

In this post, we will learn about Reflection in Java with an example.

Reflection in Java is the ability of a program to analyze itself. It is a process of examining or modifying the run time behavior of a class at run time. Reflection is an important capability, especially when using components called Java Beans. It allows you to analyze a software component and describe its capabilities dynamically, at run time rather than at compile time. For example, by using reflection, you can determine what methods, constructors, and fields a class supports.

The java.lang.reflect package provides the ability to obtain information about the fields, constructors, methods, and modifiers of a class. java.lang.reflect defines several classes, including Method, Field, and Constructor. It also defines several interfaces, including AnnotatedElement, Member, and Type. In addition, the java.lang.reflect package includes the Array class that enables you to create and access arrays dynamically.

Drawbacks of Reflection:

  • Reflection operations have slower performance than their non-reflective counterparts.
  • Reflection requires a runtime permission which may not be present when running under a security manager.
  • Reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability.

Example:

Output:

In the above program, we have tried to print the Constructors, Fields and Methods in the ReflectionDemo.java class using Reflection. The getMethods() method listed the methods from Object class as well since Object is the super class of all the classes in Java.

Other tutorials:

Cloning in Java

Related posts

Leave a Comment