java.lang.reflect package

By: Riktesh Srivastava Viewed: 153271 times  Printer Friendly Format    


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 c = Class.forName("java.lang.Object");
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);
}
}
}


Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial