- The Java Reflection API allows you to inspect and manipulate the metadata of a Java class at runtime.
- With the Reflection API, you can access class-level information, such as the class name, package, and list of fields and methods, as well as object-level information, such as the values of an object’s fields.
below is an example of using the Reflection API to inspect the metadata of a Car class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
import java.lang.reflect.Field; import java.lang.reflect.Method; public class CarReflectionExample { public static void main(String[] args) { Car car = new Car("Toyota", "Camry", 2019); Class carClass = car.getClass(); // Get the class name System.out.println("Class Name: " + carClass.getName()); // Get the fields of the class Field[] fields = carClass.getDeclaredFields(); System.out.println("Fields: "); for (Field field : fields) { System.out.println("\t" + field.getName()); } // Get the methods of the class Method[] methods = carClass.getDeclaredMethods(); System.out.println("Methods: "); for (Method method : methods) { System.out.println("\t" + method.getName()); } // Get the value of a field try { Field makeField = carClass.getDeclaredField("make"); makeField.setAccessible(true); System.out.println("Make: " + makeField.get(car)); } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } } } |
In this example, the metadata of the Car
class is accessed using the getClass
method of the Car
object.
The getDeclaredFields
and getDeclaredMethods
methods of the Class
object are then used to get the fields and methods of the class, respectively.
The value of a field can be accessed using the get
method of the Field
object, after first setting the field to be accessible using the setAccessible
method.