Introduction: Example code: import java.lang.reflect.*; public class ReflectFrameworkExample { public static void main(String[] args) throws Exception { Class<?> clazz = Class.forName("com.example.MyClass"); Field field = clazz.getDeclaredField("name"); field.setAccessible(true); Object obj = clazz.newInstance(); field.set(obj, "John Doe"); String name = (String) field.get(obj); System.out.println("Field value: " + name); Method method = clazz.getDeclaredMethod("printMessage", String.class); method.setAccessible(true); method.invoke(obj, "Hello World!"); Object newObj = clazz.newInstance(); System.out.println("New object: " + newObj); } } class MyClass { private String name; public void printMessage(String message) { System.out.println("Message: " + message); } } In this example, we first obtain the Class object for the "MyClass" class using either `Class.forName()` or `.class` keyword. Then, we use reflection to access the private field "name" and set its value. We also invoke a method "printMessage" with a string parameter. Finally, we create a new instance of the class using the `newInstance()` method. Conclusion:


上一篇:
下一篇:
切换中文