Java 反射备忘录

            Class cls = Class.forName("com.future.dream.reflex.UserInfo");
            Object obj = cls.newInstance();
            //属性的反射
            //获取public权限的属性
            Field visibleField = cls.getDeclaredField("visibleName");
            System.out.println("name="+visibleField.get(obj));
            System.out.println("FiledName="+visibleField.getName());
            //改变值
            visibleField.set(obj, "luchao");
            System.out.println("changName="+visibleField.get(obj));

            //获取private权限的属性
            Field inVisibleField = cls.getDeclaredField("inVisibleName");
            //获取private属性必须加此方法,取消java严格的权限检查,并且可提升性
           能,建议都加上
            inVisibleField.setAccessible(true);
            System.out.println("name="+inVisibleField.get(obj));
            System.out.println("FiledName="+inVisibleField.getName());

            //获取静态属性的值
            Field staticField = cls.getDeclaredField("staticName");
            System.out.println("name="+staticField.get(obj));
            System.out.println("FiledName="+staticField.getName());
            //改变静态属性的值staticField,Object可以设置成为null.
            staticField.set(null, "apple");
            System.out.println("changeName="+staticField.get(obj));

            //方法的反射
            Method setNameMethod = cls.getDeclaredMethod("setName", 
            String.class);
            setNameMethod.invoke(obj, "set name to luchao");
            Method getNameMethod = cls.getDeclaredMethod("getName");
            System.out.println("name="+ getNameMethod.invoke(obj));

你可能感兴趣的:(Java 反射备忘录)