1.
package com.recorder.ref;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @author 紫英
* @version 1.0
* @discription 反射爆破修改属性
*/
public class Homework01 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class<?> clazz = Class.forName("com.recorder.ref.PrivateTest");
Object o = clazz.newInstance();
// 得到name属性的对象
Field name = clazz.getDeclaredField("name");//因为name是private的
name.setAccessible(true);
// 得到getName方法的对象
Method getName = clazz.getMethod("getName");
name.set(o,"剋踢猫");
System.out.println(getName.invoke(o));
}
}
class PrivateTest{
private String name = "HelloKitty!";
public String getName() {
return name;
}
}
2.
package com.recorder.ref;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @author 紫英
* @version 1.0
* @discription 反射创建文件
*/
public class Homewor02 {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
Class<?> fileClass = Class.forName("java.io.File");
String filePath = "e:\\123.txt";
//取得有参构造器
Constructor<?> constructor = fileClass.getConstructor(String.class);
// 通过构造器创建file对象
Object o = constructor.newInstance(filePath);
Constructor<?>[] declaredConstructors = fileClass.getDeclaredConstructors();
for (Constructor<?> declaredConstructor : declaredConstructors) {
System.out.println(declaredConstructor);
}
// 取得方法对象
Method createNewFile = fileClass.getMethod("createNewFile");
// 调用方法创建文件
createNewFile.invoke(o);
}
}