Reflection is a runtime API for inspecting and changing the behavior of methods, classes, and interfaces. The java.lang.reflect
package contains the required reflection classes. Reflection tells about the class to which an object belongs and the methods of that class that can be used for the object. One can call the methods at runtime using reflection regardless of the access specifier used.
Reflection helps when thinking about:
getClass()
function is used to figure out what class an object belongs to.getConstructors()
function.getMethods()
method.class Demo {}interface MyInterface {}class Test {public static void main(String args[]) {try {Class c1 = Class.forName("Demo");System.out.println(c1.isInterface());Class c2 = Class.forName("MyInterface");System.out.println(c2.isInterface());}catch(Exception exp) {System.out.println(exp);}}}
Java Reflection is the process of examining or changing a class’s runtime behavior while it is still running.
Many methods in the java.lang.Class
class can be used to get metadata, analyze, and modify a class’s run-time actions.
The java.lang.Class
class primarily serves two purposes:
Classes for java reflection can be found in the java.lang
and java.lang.reflect
packages.
The Reflection API is mostly used in the following applications:
In java.lang.reflect
, one can find reflection classes like Method. To use these courses, users must first complete three steps.
The first step is to get a java.lang.Class
object for the class you would like to work in. Java.lang.Class
is the name of the Java programming language. In a running Java program, this command would be used to describe objects and interfaces.
One way to get a Class object is to type:
Class.forName("java.lang.String")
To acquire Class knowledge on fundamental classes, use: Class c = int.class;
or Class c = Integer.TYPE
.
The last method uses the wrapper’s predefined Value field (such as Integer) to reach the fundamental type.