实例代码
package sys.test;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) throws Exception {
/**
* 获取TargetObject类的Class对象并且创建TargetObject类实例
*/
Class<?> targetClass = Class.forName("sys.test.TargetObject");
TargetObject targetObject = (TargetObject) targetClass.newInstance();
/**
* 获取所有类中所有定义的方法
*/
Method[] methods = targetClass.getMethods();
for (Method m1 : methods) {
// System.out.println(m1.getName());
}
/**
* 获取指定方法并调用
*/
Method publicMethod = targetClass.getMethod("publicMethod", String.class);
publicMethod.invoke(targetObject, "you");
/**
* 获取指定参数并对参数进行修改
*/
Field value = targetClass.getDeclaredField("value");
//为了调用private方法我们取消安全检查
value.setAccessible(true);
value.set(targetObject, "zhangshan");
/**
* 调用 private 方法
*/
Method privateMethod = targetClass.getDeclaredMethod("privateMethod");
//为了调用private方法我们取消安全检查
privateMethod.setAccessible(true);
privateMethod.invoke(targetObject);
}
}
package sys.test;
public class TargetObject {
private String value;
public TargetObject() {
value = "JavaGuide";
}
public void publicMethod(String s) {
System.out.println("I love " + s);
}
private void privateMethod() {
System.out.println("value is " + value);
}
}