反射 今天学习了反射,代码简单,思路简单反射的定义:反射java语言中的一种机制,通过这种机制可以动态的实例化对象、读写属性、调用方法反射的获取非公开属性 (Declared) :Field fname = c.getDeclaredField("sname");fname.setAccessible(true);//给属性授权 truefname.set(s, "文武");判断boolean的属性是is:Field fsex = c.getDeclaredField("sex");fsex.setAccessible(true);fsex.set(s, true);System.out.println(s.isSex());通过反射获取非公开方法:Method method=c.getDeclaredMethod("add", Integer.class,Integer.class);method.setAccessible(true);System.out.println(method.invoke(s, 1,2));注意:一:一切反射相关的代码都从获得类对象开始二:ClassNotFoundException(类名错|少jar包)三:同一类的、类对象只会创建一个方法介绍:1 Class.forName(完整类名)2 类名.class3 对象.getClass例题介绍方法:1Class c = Class.forName("com.entity.Student"); //com.entity.Student是实体类的路径 // 通过类对象实例化该类 Student s = (Student) c.newInstance(); System.out.println(s);2Student s = Student.class.newInstance(); System.out.println(s);3Student s=new Student(); s.getClass().newInstance();反射三大作用:1实例化对象: c.newInstance()2动态调用方法: cls.getMethod("方法名","方法参数"); Method m; m.invoke3读写属性: public属性 cls.getFiled("age"); cls.getFileds(); private属性 cls.getDeclaredFiled(); cls.getDeclaredFileds(); Field set/get filed.getName(); filed.getType(); filed.getModifiers(); //参数1:当前对象 //参数2:需要的值 filed.set(Obj,value); //取值 flied.get(obj); //私有属性赋值 filed.setAccessible(true);4访问修饰符: getModifiers()
2021-07-15
最新推荐文章于 2022-09-08 12:39:40 发布