import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; public class ReflectionExample { private String name; // Constructor public ReflectionExample(String name) { this.name = name; } // Method to display the name public void display() { System.out.println("Hello, " + name); } public static void main(String[] args) { try { // Get the Class object Class<?> clazz = Class.forName("ReflectionExample"); // Create an instance using the constructor Constructor<?> constructor = clazz.getConstructor(String.class); Object instance = constructor.newInstance("Java Reflection"); // Invoke the display method Method displayMethod = clazz.getMethod("display"); displayMethod.invoke(instance); // Access and modify the private field Field nameField = clazz.getDeclaredField("name"); nameField.setAccessible(true); // Allow access to the private field nameField.set(instance, "Updated Name"); // Display the modified name displayMethod.invoke(instance); // Outputs: Hello, Updated Name } catch (Exception e) { e.printStackTrace(); } } }