java--反射--课后作业&知识梳理
Posted 张紫韩
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java--反射--课后作业&知识梳理相关的知识,希望对你有一定的参考价值。
- 课后练习
-
package com.model.homework; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * @Description:测试类 * @Author: 张紫韩 * @Crete 2021/6/29 23:24 */ public class HomeWorkDemo01 { public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException,
NoSuchMethodException, InvocationTargetException, NoSuchFieldException { Class<?> aClass = Class.forName("com.model.homework.PrivateTest"); Object o = aClass.newInstance(); Field name = aClass.getDeclaredField("name"); name.setAccessible(true); name.set(o, "张紫韩"); Method getName = aClass.getMethod("getName"); Object invoke = getName.invoke(o); System.out.println(invoke); } } class PrivateTest{ private String name="helloKitty"; public String getName() { return name; } }
-
-
package com.model.homework; import java.io.File; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * @Description:测试类 * @Author: 张紫韩 * @Crete 2021/6/29 23:32 */ public class HomeWorkDemo02 { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException { String path="D:\\\\qq\\\\IDEA\\\\IdeaProjects\\\\java_mianshi\\\\mianshi_fanshe\\\\src\\\\main\\\\resources\\\\mynew.txt"; Class<?> aClass = Class.forName("java.io.File"); Constructor<?>[] declaredConstructors = aClass.getDeclaredConstructors(); for (Constructor<?> declaredConstructor : declaredConstructors) { System.out.println(declaredConstructor); } Constructor<?> constructor = aClass.getDeclaredConstructor(String.class); Object o = constructor.newInstance(path); System.out.println(o.getClass()); //File类型的 Method createNewFile = aClass.getMethod("createNewFile"); createNewFile.invoke(o); System.out.println("创建文件成功"); } }
-
以上是关于java--反射--课后作业&知识梳理的主要内容,如果未能解决你的问题,请参考以下文章