/** * 定义PrivateTest类,有私有name属性,并且属性值为 hellokitty * 提供getName的公有方法 * 创建PrivateTest的类,利用 Class类行到私有时 name属性,修改私有的 name属性值,并调用getName()的方法打印 name属性值 */public class HomeWork01 { public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException { //1、得到PrivateTest类对应的Class对象 Class<PrivateTest> privateTestClass = PrivateTest.class; //2、创建对象实例 PrivateTest privateTest = privateTestClass.newInstance(); //3、得到name属性对象 Field name = privateTestClass.getDeclaredField("name"); //4、因为name属性是private私有的,爆破name name.setAccessible(true); name.set(privateTest,"gyc"); //5、得到getName方法对象 Method getName = privateTestClass.getMethod("getName"); //6、因为getName是public,所以直接调用 System.out.println(getName.invoke(privateTest)); } } class PrivateTest{ private String name = "hellokitty"; public String getName() { return name; } }
输出:gyc
/** * 1.利用 Class类的 forName方法得到 File类的 class对象 * 2.在控制台打印 File类的所有构造器 * 3.通过 newInstance 的方法创建 File对象,并创建E:\mynew.txt文件 */public class HomeWork02 { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { Class<?> fileClass = Class.forName("java.io.File"); Constructor<?>[] declaredConstructors = fileClass.getDeclaredConstructors(); //遍历输出 for (Constructor<?> declaredConstructor : declaredConstructors) { System.out.println("File构造器:" + declaredConstructor); } //3、指定的得到 public java.io.File(java.lang.String) Constructor<?> declaredConstructor = fileClass.getDeclaredConstructor(String.class); String fileAllPath = "d:\\mynew.txt"; Object file = declaredConstructor.newInstance(fileAllPath);//创建File对象 //4.得到createNewFile 的方法对象 Method createNewFile = fileClass.getMethod("createNewFile"); createNewFile.invoke(file);//创建文件,调用的是 createNewFile // file的运行类型就是File System.out.println(file.getClass()); System.out.println("创建文件成功" + fileAllPath); } }
输出:
File构造器:public java.io.File(java.lang.String,java.lang.String)
File构造器:public java.io.File(java.lang.String)
File构造器:private java.io.File(java.lang.String,java.io.File)
File构造器:public java.io.File(java.io.File,java.lang.String)
File构造器:public java.io.File(java.net.URI)
File构造器:private java.io.File(java.lang.String,int)
class java.io.File
创建文件成功d:\mynew.txt