In this tutorial, I will explain the aspects of java.lang.reflect package. This package returns, constructors, fields, and methods of the given package. Each and every program begins by using the forName() method of Class to get a class object for java.lang.Object. Once this is obtained, getConstructors(), getFields(), and getMethods() are used to analyze this class object. They return arrays of Constructor, Field, and Method objects that provide the information about the object. The Constructor, Field, and Method classes define several methods that can be used to obtain information about an object.
Consider the example given below:
import java.lang.reflect.*;
class program {
public static void main(String args[]) {
try {
Class<Object> c = Object.class;
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);
}
}
}
The given program demonstrates the use of Java reflection to get information about the class "java.lang.Object". Here's how it works:
- The program first calls the
Class.forName()method to get a reference to thejava.lang.Objectclass. - The
getConstructors()method is then called on theClassobject to retrieve an array ofConstructorobjects that represent the public constructors of the class. - A
forloop is used to iterate over theConstructorarray and print each constructor to the console. - Similarly, the
getFields()method is called on theClassobject to retrieve an array ofFieldobjects that represent the public fields of the class. Anotherforloop is used to print each field to the console. - Finally, the
getMethods()method is called on theClassobject to retrieve an array ofMethodobjects that represent the public methods of the class. Anotherforloop is used to print each method to the console.
Here's an example output of the program:
Constructors: public java.lang.Object() Fields: public static final java.lang.Class java.lang.Object.CLASS Methods: public boolean java.lang.Object.equals(java.lang.Object) public java.lang.String java.lang.Object.toString() public native int java.lang.Object.hashCode() public final native java.lang.Class java.lang.Object.getClass() public final native void java.lang.Object.notify() public final native void java.lang.Object.notifyAll() public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException public final void java.lang.Object.wait() throws java.lang.InterruptedException public final void java.lang.Object.wait(long) throws java.lang.InterruptedException