1.设计一个方法如下,要求该方法能修改任意对象中,指定成员变量的值
public class day2801 {
/**
* @param targetObj 要修改成员变量值的目标对象
* @param fieldName 对象中要修改的成员变量的名字
* @param newValue 要修改成员变量值的新值
*/
public static void setAll(Object targetObj, String fieldName, Object newValue) throws NoSuchFieldException, IllegalAccessException {
//创建要修改成员变量值的目标对象
Class targetObjClass = targetObj.getClass();
//对象中要修改的成员变量的名字
Field declaredField = targetObjClass.getDeclaredField(fieldName);
//解决权限问题,让jvm绕过权限检查机制
declaredField.setAccessible(true);
//在指定对象上修改成员变量值的新值
declaredField.set(targetObj, newValue);
//验证fieldName的值已经改变
System.out.println(targetObj);
}
}
该方法利用反射,可以修改私有成员变量的值
2.完成如下方法,要求该方法能调用,指定配置文件中,指定类中指定的普通成员方法(无参方法) 假设指定类中一定有默认构造方法
public class Work2 {
/**
*
* @param configFilePath 表示配置文件的路径
*/
public void callTargetMethod(String configFilePath) {
}
}
public class day2802 {
/**
* @param configFilePath 表示配置文件的路径
*/
public void callTargetMethod(String configFilePath) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
//1.读取配置文件信息,将去读取到我们的Properties对象中
Properties properties = loadConfigFileInfo(configFilePath);
//2.从Properties对象中,获取指定类的全类名和指定的方法名
String className = properties.getProperty("className");
String methodName = properties.getProperty("methodName");
//通过全类名,获取全类名所指定的类的类型信息(访问对应的Class)
Class targetClass = Class.forName(className);
//利用反射,从targetClass中获取目标方法的method对象
Method targetMethod = targetClass.getDeclaredMethod(methodName);
//绕过jvm检查机制
targetMethod.setAccessible(true);
//利用反射创建目标对象(Constructor对象.newInstance(),利用无参构造方法)
Constructor declaredConstructor = targetClass.getDeclaredConstructor();
declaredConstructor.setAccessible(true);
//利用反射,创建目标对象
Object targetObj = declaredConstructor.newInstance();
//在目标对象上,调用执行Method对象表示的方法,并传递参数(Method对象.invoke(目标对象))
targetMethod.invoke(targetObj);
}
private Properties loadConfigFileInfo(String configFilePath) throws IOException {
Properties properties = new Properties();
properties.load(new FileInputStream(configFilePath));
return properties;
}
}
思路:利用properties 读取配置文件的className和classMethod,然后利用反射机制调用method.