2021-07-15

   反射  今天学习了反射,代码简单,思路简单反射的定义:反射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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值