What is Java Reflection? Write a simple program to demonstrate it
Introduction
Java Reflection is a mechanism for manipulating classes, interfaces, and objects at the runtime of the Java program. Reflection API consists of methods to introspect the class at runtime.
Using Reflection you can create an instance of a class whose name is not known until runtime. Invoke methods on an object, set and get accessors and mutators for an object’s field which is unknown until runtime.
Class object
For every loaded class, the Java Runtime Environment maintains an associated Class object. The Class object “reflects” the class it represents
You can use the Class object to discover information about a loaded class
• name
• modifiers
• superclasses
• implemented interfaces
• fields
• methods
• constructors
Sample ways to access the Class object for a loaded class
To get the Class object for an object notKnownAtRuntime
Class clz = notKnownAtRuntime.getClass();
By using the class name
Class clz = Class.forName(“myClass”);
or
Class clz = Class.forName(“com.testingdocs.sample.program.SampleClass”);
To import and use Reflection API we have to use the below statement.
import java.lang.reflect.*;
Java Program
In the below program we will print all the method names of Object class.
import java.lang.reflect.*; public class ReflectionExample { public static void main(String[] args) { try { Object obj = new Object(); printMethodNames(obj); } catch (Exception e) { System.out.println(e); } } static void printMethodNames(Object o) { Class<?> c = o.getClass(); System.out.println("Method names of :" + c.getName() + " class"); Method[] methods = c.getMethods(); for (int i = 0; i < methods.length; i++) { String methodName = methods[i].getName(); System.out.println(methodName + "()"); } } }
Program output
Method names of :java.lang.Object class
wait()
wait()
wait()
equals()
toString()
hashCode()
getClass()
notify()
notifyAll()