Introduction
The process of finding Constructors, Fields, and Methods in a class In Java programming language is done by the Reflection API in Java. Reflection is commonly used by programs which require the ability to examine or modify the runtime behaviour of applications running in the Java virtual machine.
What is Reflection API in Java?
It is possible to use Reflection in Java; Java provides the API in a package named "reflect". Reflection is a feature in the Java programming language. Reflection allows an executing Java program to "introspect" itself, and manipulate internal properties of the program. For example, it is possible for a Java class that has n number of constructors, methods, and fields to be accessed; the details of all the functions (methods) with help of appropriate Class of the reflect package; for example you want to find the constructor of a class then you can use the Constructor class.
Constructor class
Using the Constructor class of the Java reflection API, you can inspect the Constructors of classes and instantiate objects at runtime.
Example
- import java.lang.reflect.Constructor;
- public class FindConstructor
- {
- public static void main(String args[])
- {
- try {
-
- Class c = Class.forName("java.io.BufferedInputStream");
- System.out.println("Constructors:");
-
- Constructor constructors[] = c.getConstructors();
- for (int i = 0; i < constructors.length; i++)
- System.out.println(+i + "-" + constructors[i]);
- } catch (Exception e) {
- System.out.println("Exception: " + e);
- }
- }
- }
0utput
Fields Class
Using the Field class of the Java reflection API you can inspect the Fields of classes and obtain the object's field name, type and the getting and setting fields value.
Example
- import java.lang.reflect.Field;
- public class MyField
- {
- public static void main(String args[])
- {
- try {
-
- Class c = Class.forName("java.lang.reflect.Field");
- System.out.println("Fields:");
- Field fields[] = c.getFields();
- for (int i = 0; i < fields.length; i++)
- System.out.println(+i + "- " + fields[i]);
- } catch (Exception e) {
- System.out.println("Exception: " + e);
- }
- }
- }
Output
Method class
A Method
class providing information about, and access to, a single method on a class or interface. The reflected method may be a class method or an instance method (including an abstract method).
Example
- import java.lang.reflect.Method;
- public class MyMethod
- {
- public static void main(String args[])
- {
- try
- {
-
-
- Class c = Class.forName("java.lang.reflect.Method");
- System.out.println("methods:");
- Method methods[] = c.getMethods();
- for (int i = 0; i < methods.length; i++)
- System.out.println(+i+"- " + methods[i]);
- }
- catch (Exception e)
- {
- System.out.println("Exception: " + e);
- }
- }
- }
Output
Summary
With the help of this article, you can access any field, constructor or method of any class and you can get the internal structure of an unknown class so Reflection has its importance.