java的反射手写示例代码
首先创建需要动态加载的类
1 package classloader; 2 3 public class TestClass { 4 private String value; 5 public TestClass() { 6 value = "123"; 7 } 8 public void publicMethod(String s) { 9 System.out.println("i love " + s); 10 } 11 private void privateMethod() { 12 System.out.println("value is " + value); 13 } 14 }
通过反射加载类
package classloader; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Main { public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException { // 获取TestClass类的Class对象 Class<?> testClass=Class.forName("classloader.TestClass"); // 创建TestClass类实例 TestClass testClassObject= (TestClass) testClass.newInstance(); // 获取Class类的方法 Method[] methods=testClass.getDeclaredMethods(); for (Method method : methods) { System.out.println(method); } // 获取指定方法并调用 Method publicMethod = testClass.getDeclaredMethod("publicMethod", String.class); publicMethod.invoke(testClassObject,"zhanghs"); //获取指定参数并对参数进行修改 Field field = testClass.getDeclaredField("value"); //私有变量取消安全检查 field.setAccessible(true); field.set(testClassObject,"zhanghaos"); // 调用 private 方法 Method privateMethod=testClass.getDeclaredMethod("privateMethod"); //私有方法也需取消安全检查 privateMethod.setAccessible(true); privateMethod.invoke(testClassObject); } }

浙公网安备 33010602011771号