Java--反射--课后作业&知识梳理

  1. 课后练习
      1. 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; } }
      1.  

        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("创建文件成功");
        
            }
        }  
posted @ 2021-06-29 23:53  张紫韩  阅读(48)  评论(0编辑  收藏  举报