English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, we will learn about reflection, which is a feature in Java programming that allows us to inspect and modify classes, methods, and so on.
In Java, reflection allows us to inspect and manipulate classes, interfaces, constructors, methods, and fields at runtime.
Before learning Java reflection, we need to understand a Java class named Class.
In Java, there is a class named Class, which retains all information about objects and classes at runtime.
The Class object describes the properties of a specific class. This object is used to perform reflection.
We can create a Class object by:
Use forName() method
The forName() method accepts a string parameter (the name of the class) and returns a Class object. The returned object refers to the class specified by the string. For example,
Class Dog { } Class c1 = Class.forName("Dog");
Use getClass() method
The getClass() method uses an object of a specific class to create a new object Class. For example,
Dog d1 = new Dog() Class c1 = d1.getClass();
Use .class
We can also use.classCreate a Class object using an extension name. For example,
Class c1 = Dog.class;
After creating a Class object, we can use these objects to perform reflection.
We can use the Class.getInterfaces() method to collect information about the interfaces implemented by the class. This method returns an array of interfaces.
import java.lang.Class; import java.lang.reflect.*; interface Animal { public void display(); } interface Mammal { public void makeSound(); } class Dog implements Animal, Mammal { public void display() { System.out.println("I am a dog."); } public void makeSound() { System.out.println("Bark bark"); } } class ReflectionDemo { public static void main(String[] args) { try { //Create an object of the Dog class Dog d1 = new Dog(); //Create a Class object using getClass() Class obj = d1.getClass(); //Find interfaces implemented by Dog Class[] objInterface = obj.getInterfaces(); for(Class c : objInterface) { //Print interface name System.out.println("Interface Name: ") + c.getName()); } } catch(Exception e) { e.printStackTrace(); } } }
Output Result
Interface Name: Animal Interface Name: Mammal
The method getSuperclass() of the class Class can be used to get information about the superclass of a specific class.
Moreover, the Class provides a getModifier() method that returns the modifiers of the class as an integer.
import java.lang.Class; import java.lang.reflect.*; interface Animal { public void display(); } public class Dog implements Animal { public void display() { System.out.println("I am a dog."); } } class ReflectionDemo { public static void main(String[] args) { try { //Create an object of the Dog class Dog d1 = new Dog(); //Create a Class object using getClass() Class obj = d1.getClass(); //Get the access modifiers of Dog as an integer int modifier = obj.getModifiers(); System.out.println("Modifier: ", + Modifier.toString(modifier)); //Find the superclass of Dog Class superClass = obj.getSuperclass(); System.out.println("Superclass: ", + superClass.getName()); } catch(Exception e) { e.printStackTrace(); } } }
Output Result
Modifier: public Superclass: Animal
The package java.lang.reflect provides classes that can be used to operate on class members. For example,
Method class - Provide information about the methods in the class
Field class - Provide information about the fields in the class
Constructor class - Provide information about the constructors in the class
We can use various methods provided by the Field class to check and modify different fields of the class.
getFields() - Return all public fields of the class and its superclasses
getDeclaredFields() - Return all fields of the class
getModifier() - Return the modifiers of the field as an integer
set(classObject, value) - Set the value of the field with the specified value
get(classObject) - Get the value of the field
setAccessible(boolean) - Make the private field accessible
Note:If we know the field name, we can use
getField("fieldName") - Return the name of the class fromfieldNamethe public field.
getDeclaredField("fieldName") - Return the name of the class fromfieldNamefield.
import java.lang.Class; import java.lang.reflect.*; class Dog { public String type; } class ReflectionDemo { public static void main(String[] args) { try{ Dog d1 = new Dog(); //Create a Class object Class obj = d1.getClass(); //Manipulate the public field type of the Dog class Field field1 = obj.getField("type"); //Set the value of the field field1.set(d1, "labrador"); //Get the value of the field by converting it into a string String typeValue = (String)field1.get(d1); System.out.println("type: ", + typeValue); //Get the access modifier of the type int mod1 = field1.getModifiers(); String modifier1 = Modifier.toString(mod1); System.out.println("Modifier: ", + modifier1); System.out.println(" "); } catch(Exception e) { e.printStackTrace(); } } }
Output Result
type: labrador Modifier: public
import java.lang.Class; import java.lang.reflect.*; class Dog { private String color; } class ReflectionDemo { public static void main(String[] args) { try { Dog d1 = new Dog(); //Create a class Class object Class obj = d1.getClass(); //Access the private field Field field2 = obj.getDeclaredField("color"); //Make the private field accessible field2.setAccessible(true); //Set the color value field2.set(d1, "brown"); // Get the value of the type converting in String String colorValue = (String)field2.get(d1); System.out.println("color: ", + colorValue); //Get the access modifier of color int mod2 = field2.getModifiers(); String modifier2 = Modifier.toString(mod2); System.out.println("modifier: ", + modifier2); } catch(Exception e) { e.printStackTrace(); } } }
Output Result
color: brown modifier: private
Like fields, we can use various methods provided by the Method class to check different methods of the class.
getMethods() - Return all public methods of the class and its superclasses
getDeclaredMethod() - Return all methods of the class
getName() - Return the name of the method
getModifiers() - Return the access modifier of the method in integer form
getReturnType() - Return the return type of the method
import java.lang.Class; import java.lang.reflect.*; class Dog { public void display() { System.out.println("I am a dog."); } protected void eat() { System.out.println("I eat dog food."); } private void makeSound() { System.out.println("Bark Bark"); } } class ReflectionDemo { public static void main(String[] args) { try { Dog d1 = new Dog(); //Create a Class object Class obj = d1.getClass(); //Use getDeclaredMethod() to get all methods Method[] methods = obj.getDeclaredMethods(); //Get the name of the method for(Method m : methods) { System.out.println("Method name: "); + m.getName()); //Get the access modifier of the method int modifier = m.getModifiers(); System.out.println("Modifier: ", + Modifier.toString(modifier)); //Get the return type of the method System.out.println("Return Types: "); + m.getReturnType()); System.out.println(" "); } } catch(Exception e) { e.printStackTrace(); } } }
Output Result
Method name: display Modifier: public Return type: void Method name: eat Modifier: protected Return type: void Method name: makeSound Modifier: private Return type: void
We can also use various methods provided by the Constructor class to check different constructors of the class.
getConstructors() - Return all public constructors of the class and its superclass
getDeclaredConstructor() -Return all constructors
getName() - Return the name of the constructor
getModifiers() - Return the access modifier of the constructor in integer form
getParameterCount() - Return the number of constructor parameters
import java.lang.Class; import java.lang.reflect.*; class Dog { public Dog() { } public Dog(int age) { } private Dog(String sound, String type) { } } class ReflectionDemo { public static void main(String[] args) { try { Dog d1 = new Dog(); Class obj = d1.getClass(); //Obtain all constructors of a class using getDeclaredConstructor() Constructor[] constructors = obj.getDeclaredConstructors(); for(Constructor c : constructors) { //Get the name of the constructor System.out.println("Constructor Name: ", + c.getName()); //Get the access modifier of the constructor int modifier = c.getModifiers(); System.out.println("Modifier: ", + Modifier.toString(modifier)); //Get the number of parameters in the constructor System.out.println("Number of Parameters: ", + c.getParameterCount()); } } catch(Exception e) { e.printStackTrace(); } } }
Output Result
Constructor Name: Dog Modifier: public Number of Parameters: 0 Constructor Name: Dog Modifier: public Number of Parameters: 1 Constructor Name: Dog Modifier: private Number of Parameters: 2