首先,创建一个类,动态加载的测试类
package classloader;
public class TestClass {
private String value;
public TestClass() {
value = "123";
}
public void publicMethod(String s) {
System.out.println("i love " + s);
}
private void privateMethod() {
System.out.println("value is " + value);
}
}
通过反射去执行测试类的方法,和修改测试类的变量值
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);
}
}
这就是反射的基础运用