Java Reflection helps us to read or modify metadata related to class, fields, methods and constructors at run time.
It allow us to fetch or get metadata information like scope, modifier, name, parameters, method invocation etc. related to class, field, constructor and method.
java.lang.reflect package is having Field, Method, Constructor classes which provides us the capability to fetch or modify public as well as private metadata related to class, field, constructor and method.
isInterface(), getSuperclass(), getName(), getClass(), getMethods(), getFields(), .getConstructors() are some of the common and most used method from java.lang.Class class to get or fetch metadata.
Below are the steps to get or read metadata using reflection:
It require a java.lang.Class class object to get the metadata using reflection. Below are the methods allow us to get metadata using reflection:
forName() static method from java.lang.Class class allow us to create or get Class object.
getClass() native final method from java.lang.Object class also allow us to get java.lang.Class class object.
.class extension also allow us to get java.lang.Class class object as shown below:
Below is an example to access class fields metadata such as field name, modifier, get or set value etc. using reflection.
OUTPUT:
firstName
lastName
age
Below is reflection example to access private field name from Student class.
OUTPUT
Name =John
Is Interface = false
Below is an example to set age field value of Student class using reflection:
OUTPUT
age = 0
age = 12
Below is an example to access method metadata such as method name, parameters and its type, modifiers, method invocation using reflection.
OUTPUT:
Method: private void com.practice.core.Student.getStudentName(java.lang.String)
Declaring Class: com.practice.core.Student
Parameter Type: [Ljava.lang.Class;@246ae04d
Return Type: void
Below is an example to invoke method using Class.forName() method using reflection:
Below is an example to access constructor and get its metadata such as constructor name, parameters and its type, modifiers using reflection.
OUTPUT
Below are some of the disadvantages of using the reflection API:
Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.
📝 Blogs
javadoubts.com © All rights reserved