Reflection API Java

Studying the properties of a class at runtime is known Reflection (in JavaBeans, this is called as Introspection). The properties include knowing the instance variables, constructors and methods with their access specifiers and modifiers. Generally reflection is used by JVM and tools that loads a class and do operations on the class like calling methods and accessing constructors etc. Reflection is more used by tool developers to inspect the class, after loading into the RAM by the class loader, dynamically (at runtime). Introduced with JDK 1.1 version, reflection is one of the strengths of Java where a Java program is expected to run on any platform where classes are loaded dynamically, objects are created on the fly as when required by the runtime environment.

To put it simply, the Reflection API allows the running Java program to query a class about its fields, methods, access specifiers and so on. It can instantiate the class, invoke the methods or access the fields, even if the class was unknown when the program was compiled.

It is primarily useful for tool builders, not for application programmers. JavaBeans, the component technology of Java, relies heavily on Reflection API and the Builder tools use the Reflection API to load new beans at runtime and query them for their abilities.

The Reflection API is built from the java.lang.Class class and the java.lang.reflect package. This package contains classes representing fields, methods, constructors and utility classes for working with arrays and modifiers.

The java.lang.reflect Package

The java.lang.reflect package defines one interface, five classes and one exception. The classes are

  1. Array
  2. Constructor
  3. Field
  4. Method
  5. Modifier

Each of the above classes represents an essential part of the signature of a Java class. There is also a Member interface, which is implemented by Field, Constructor and Method; and an InvocationTargetException exception, which is thrown by several of the methods in this package.

Leave a Comment

Your email address will not be published.