练习一
- 定义 PrivateTest 类,有私有 name 属性,并且属性值为 hellokitty
- 提供 getName 的公有方法
- 创建 PrivateTest 的类,利用 Class 类得到私有的 name 属性,修改私有的 name 属性值,并调用 getName() 的方法打印 name 属性值
package reflection_;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @Author: Gin
* @Description:
* @Modified By: Gin
* @Date: Created in 10:56 2021/9/30
*/
public class ReflectWork {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException {
/*
1. 定义 PrivateTest 类,有私有 name 属性,并且属性值为 hellokitty
2. 提供 getName 的公有方法
3. 创建 PrivateTest 的类,利用 Class 类得到私有的 name 属性,修改私有的 name 属性值,
并调用 getName() 的方法打印 name 属性值
*/
// 1. 得到 PrivateTest 的 Class 对象
Class<?> aClass = Class.forName("reflection_.PrivateTest");
// 2. 创建对象
Object o = aClass.newInstance();
// 3. 得到 name 属性对象
Field name = aClass.getDeclaredField("name");
// 4. 爆破 name,因为 name 是 private 的,必须先爆破,才能进行操作
name.setAccessible(true);
name.set(o, "Gin");
// 5. 得到 getName 方法对象
Method getName = aClass.getMethod("getName");
// 6. 因为 getName() 是 public 的,所以直接调用
Object invoke = getName.invoke(o);
System.out.println("getName() 返回的值:" + invoke); // Gin
}
}
class PrivateTest{
private String name = "hellokitty";
public String getName(){
return name;
}
}
练习二
- 利用 Class 类的 forName 方法得到 File 类的 class 对象
- 在控制台打印 File 类的所有构造器
- 通过 newlnstance 的方法创建 File 对象,并创建 E:\mynew.txt 文件
提示:创建文件的正常写法如下:
File file = new File(d:\\aa.txt");
//内存
file.createNewFile();
//方法,才能真正的创建文件
package reflection_;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @Author: Gin
* @Description:
* @Modified By: Gin
* @Date: Created in 11:08 2021/9/30
*/
public class ReflectWork2 {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
// 1. 利用 Class 类的 forName 方法得到 File 类的 class 对象
Class<?> fileCls = Class.forName("java.io.File");
// 2. 在控制台打印 File 类的所有构造器
Constructor<?>[] declaredConstructors = fileCls.getDeclaredConstructors();
for (Constructor constructor : declaredConstructors) {
System.out.println("java.io.File 的所有构造器:" + constructor);
}
// 3. 通过 newlnstance 的方法创建 File 对象,并创建 E:\mynew.txt 文件
// 3.1 指定得到 public java.io.File(java.lang.String);
Constructor<?> declaredConstructor = fileCls.getDeclaredConstructor(String.class);
String filePath = "E:\\mynew.txt";
Object o = declaredConstructor.newInstance(filePath); // 创建 file 对象
// 4. 得到 createNewFile 的方法对象
Method createNewFile = fileCls.getMethod("createNewFile");
createNewFile.invoke(o); // 创建文件,调用的是 createNewFile() 方法
// o 的运行类型就是 File
System.out.println("o 的运行类型:" + o.getClass());
System.out.println("创建文件成功:" + filePath);
}
}