Java Tutorials
What is Garbage Collection in Java?
What is Garbage Collection in Java? Garbage Collection in Java is a process by which the programs...
Java Reflection is the process of analyzing and modifying all the capabilities of a class at runtime. Reflection API in Java is used to manipulate class and its members which include fields, methods, constructor, etc. at runtime.
One advantage of reflection API in Java is, it can manipulate private members of the class too.
The java.lang.reflect package provides many classes to implement reflection java.Methods of the java.lang.Class class is used to gather the complete metadata of a particular class.
In this tutorial, you will learn-
Following is a list of various Java classes in java.lang.package to implement reflection-
public class gtupapersClassObjectCreation {
public static void main (String[] args) throws ClassNotFoundException {
//1 - By using Class.forname() method
Class c1 = Class.forName("gtupapersClassObjectCreation");
//2- By using getClass() method
gtupapersClassObjectCreation gtupapersObj = new gtupapersClassObjectCreation();
Class c2 = gtupapersObj.getClass();
//3- By using .class
Class c3= gtupapersClassObjectCreation.class;
}
}
Following example shows how to get metadata such as: Class name, super class name, implemented interfaces, and access modifiers of a class.
We will get the metadata of below class named gtupapersBase.class:
import java.io.Serializable;
public abstract class gtupapersBase implements Serializable,Cloneable {
}
import java.lang.reflect.Modifier;
public class gtupapersGetclassMetaData {
public static void main (String [] args) throws ClassNotFoundException {
// Create Class object for gtupapersBase.class
Class gtupapersClassObj = gtupapersBase.class;
// Print name of the class
system.out.println("Name of the class is : " +gtupapersClassObj.getName());
// Print Super class name
system.out.println("Name of the super class is : " +gtupapersClassObj.getSuperclass().getName());
// Get the list of implemented interfaces in the form of Class array using getInterface() method
class[] gtupapersInterfaceList = gtupapersclassObj.getInterfaces();
// Print the implemented interfaces using foreach loop
system.out.print("Implemented interfaces are : ");
for (Class gtupapersclass1 : quru99 InterfaceList) {
system.out.print gtupapersclass1.getName() + " ");
}
system.out.println();
//Get access modifiers using get Modifiers() method and toString() method of java.lang.reflect.Modifier class
int gtupapersAccessModifier= gtupapersclassObj.getModifiers();
// Print the access modifiers
System.Out.println("Access modifiers of the class are : " +Modifier.tostring(gtupapersAccessModifier));
}
}
Following examples shows how to get metadata of variable:
Here, we are creating a class named gtupapersVariableMetaData .class with some variables:
package guru;
public class gtupapersVariableMetaData {
public static int gtupapersIntVar1=1111;
static int gtupapersIntVar2=2222;
static String gtupapersStringVar1="gtupapers.com";
static String gtupapersStringVar2="Learning Reflection API";
}
gtupapersVariableMetaData gtupapersClassVar = new gtupapersVariableMetaData(); Class gtupapersClassObjVar = gtupapersClassVar.getClass();
Field[] gtupapersField1= gtupapersClassObjVar .getFields(); Field[] gtupapersFiel2= gtupapersClassObjVar .getDeclaredFields();
getFields() method returns metadata of the public variable from the specified class as well as from its super class.
getDeclaredFields() method returns metadata of the all the variables from the specified class only.
Here, xxx could be a byte or short of any type of value we want to fetch.
Here, we are writing a class to get the metadata of the variables present in the class gtupapersVariableMetaData .class:
package guru;
import java.lang.reflect.Field;
public class gtupapersVariableMetaDataTest {
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
// Create Class object for gtupapersVariableMetaData.class
gtupapersVariableMetaData gtupapersClassVar = new gtupapersVariableMetaData();
Class gtupapersClassObjVar = gtupapersClassVar.getClass();
// Get the metadata of all the fields of the class gtupapersVariableMetaData
Field[] gtupapersField1= gtupapersClassObjVar.getDeclaredFields();
// Print name, datatypes, access modifiers and values of the varibales of the specified class
for(Field field : gtupapersField1) {
System.out.println("Variable name : "+field.getName());
System.out.println("Datatypes of the variable :"+field.getType());
int gtupapersAccessModifiers = field.getModifiers();
System.out.printlln("Access Modifiers of the variable : "+Modifier.toString(gtupapersAccessModifiers));
System.out.println("Value of the variable : "+field.get(gtupapersClassVar));
System.out.println();
system.out.println("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *") ;
}
}
}
Following examples shows how to get metadata of a method:
Here, we are creating a class named gtupapersMethodMetaData .class with some methods
package guru;
import java.sql.SQLException;
public class gtupapersMethodMetaData {
public void gtupapersAdd(int firstElement, int secondElement , String result)
throws ClassNotFoundException, ClassCastException{
System.out.println("Demo method for Reflextion API");
}
public String gtupapersSearch(String searchString)
throws ArithmeticException, InterruptedException{
System.out.println("Demo method for Reflection API");
return null;
}
public void gtupapersDelete(String deleteString)
throws SQLException{
System.out.println("Demo method for Reflection API");
}
} Steps to get the metadata about the methods in the above class :
gtupapersMethodMetaData gtupapersClassVar = new gtupapersMethodMetaData (); Class gtupapersClassObjVar = gtupapersClassVar.getClass();
Method[] gtupapers Method 1= gtupapersClassObjVar .get Methods(); Method [] gtupapers Method 2= gtupapersClassObjVar .getDeclared Method s();
getMethods() method returns metadata of the public methods from the specified class as well as from its super class.
getDeclaredMethods() method returns metadata of the all the methods from the specified class only.
Here, we are writing a class to get the metadata of the methods present in the class gtupapersMethodMetaData.class:
package guru;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class gtupapersMethodMetaDataTest {
public static void main (String[] args) {
// Create Class object for gtupapersMethod MetaData.class
class gtupapersClassObj = gtupapersMethodMetaData.class;
// Get the metadata or information of all the methods of the class using getDeclaredMethods()
Method[] gtupapersMethods=gtupapersclassObj.getDeclaredMethods();
for(Method method : gtupapersMethods) {
// Print the method names
System.out.println("Name of the method : "+method.getName());
// Print return type of the methods
System.out.println("Return type of the method : "+method.getReturnType());
//Get the access modifier list and print
int gtupapersModifierList = method.getModifiers();
System.Out.printlin ("Method access modifiers : "+Modifier.toString(gtupapersModifierList));
// Get and print parameters of the methods
Class[] gtupapersParamList= method.getParameterTypes();
system.out.print ("Method parameter types : ");
for (Class class1 : gtupapersParamList){
System.out.println(class1.getName()+" ");
}
System.out.println();
// Get and print exception thrown by the method
Class[] gtupapersExceptionList = method. getExceptionTypes();
system.out.print("Excpetion thrown by method :");
for (Class class1 : gtupapersExceptionList) {
System.out.println (class1.getName() +" "):
}
System.Out.println();
system.out.println("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ");
}
}
}
Following examples shows how to get metadata of constructors:
Here, we are creating a class named gtupapersConstructor.class with different constructors:
package guru;
import java.rmi.RemoteException;
import java.sql.SQLException;
public class gtupapersConstructor {
public gtupapersConstructor(int no) throws ClassCastException ,ArithmeticException{ }
public gtupapersConstructor(int no, String name) throws RemoteException ,SQLException{ }
public gtupapersConstructor(int no, String name, String address) throws InterruptedException{ }
}Here, we are writing a class to get the metadata of the constructors present in the class gtupapersConstructor.class:
package guru;
import java.lang.reflect.Constructor;
public class gtupapersConstructorMetaDataTest {
public static void main (String[] args) {
// Create Class object for gtupapersConstructor.class
Class gtupapersClass=gtupapersConstructor.class;
// Get all the constructor information in the Constructor array
Constructor[] gtupapersConstructorList = gtupapersClass.getConstructors();
for (Constructor constructor : gtupapersConstructorList) {
// Print all name of each constructor
System.out.println("Constrcutor name : "+constructor.getName());
//Get and print access modifiers of each constructor
int gtupapersModifiers= constructor.getModifiers();
System.Out.printlin ("Constrctor modifier : "+Modifier.toString(gtupapersModifiers));
// Get and print parameter types
Class[] gtupapersParamList=constructor.getParameterTypes();
System.out.print ("Constrctor parameter types :");
for (Class class1 : gtupapersParamList) {
System.out.println(class1.getName() +" ");
}
System. out.println();
// Get and print exception thrown by constructors
Class[] gtupapersExceptionList=constructor.getFxceptionTypes();
System.out.println("Exception thrown by constructors :");
for (Class class1 : gtupapersExceptionList) {
System.out.println(class1.getName() +" ");
}
System.out.println();
System.out.println("*******************************************");
}
}
}
Summary:
What is Garbage Collection in Java? Garbage Collection in Java is a process by which the programs...
What is JDK? JDK is a software development environment used for making applets and Java...
What is indexOf() Method in Java? indexOf() Method is used to get index of the first occurrence of a...
There are many tools available for Java management. These software ease the entire process of...
What is Interface? The interface is a blueprint that can be used to implement a class. The...
What is JasperReports for Java? JasperReports is an open-source reporting tool for Java that is...