反射
获取对象的三种方法
反射主要是针对于类加载器阶段的(仅仅代表自己的见解,如有错误请多多谅解)
截图来自黑马程序员
反射的常用方法
获取构造方法:
getConstructors() //获取全部类的构造方法 getConstructors(无) //获取无参构造的 Class<?> aClass = Class.forName("tcu.se.entity.Student"); Constructor<?> constructor = aClass.getConstructor(); constructor.newInstance(); getConstructors(String.class,int.class); // 获取有参的构造方法 Class<?> aClass = Class.forName("tcu.se.entity.Student"); Constructor<?> constructor2 = aClass.getConstructor(int.class,String.class); constructor2.newInstance(3,"slf");
成员方法
getMethods() //获取公开的所有方法,以及从父类中继承的方法。 getDeclareMethods() //获取本类的所有方法,包括私有方法,但不包括从父类中继承的 //单个无参数无返回值的方法 getMethod() : Class cls=Class.forName("tcu.se.entity.Student"); Object boj=cls.newInstance(); //创建对象 Method method1=cls.getMethod("show"); //获取方法 method1.invoke(boj); //第一个参数是对象,利用对象来调用方法 //单个有参数无返回值的方法 getMethod() Class cls=Class.forName("tcu.se.entity.Student"); Object boj=cls.newInstance(); Method method1=cls.getMethod("show2",int.class); method1.invoke(boj,34); //私有方法 getDeclareMethod() Class cls=Class.forName("tcu.se.entity.Student"); Object boj=cls.newInstance(); Method method1=cls.getDeclaredMethod("show2",int.class); method1.setAccessible(true); //但在访问中必须要设置private失效setAccissible(true); method1.invoke(boj,34); //静态方法 // 因为静态方法类名。方法名 Object boj=cls.newInstance(); Method method1=cls.getMethod("show2",int.class); // 因为静态方法类名。方法名 method1.invoke(null,34); //任何对象的通用方法 invokeAny(Object obj,String methodNme,Class<?>[] type,Object...args) 对象 方法名 方法的参数 参数的值
成员属性
getFields() //获取了的公共成员变量 getDeclareFields() //获取本类所有的变量,包括私有变量 //成员方法 getDeclareField() Class<?> aClass = Class.forName("tcu.se.entity.Student"); Field name =aClass.getDeclaredField("name"); Object o = aClass.newInstance(); name.set(o,"张三"); System.out.println(name.get(o)); //私有的成员方法 getDeclareField() Class<?> aClass = Class.forName("tcu.se.entity.Student"); Field name =aClass.getDeclaredField("name"); name.setAccessible(true); Object o = aClass.newInstance(); name.set(o,"张三"); System.out.println(name.get(o));