day32 反射机制

2017-08-03  本文已影响0人  路人爱早茶

1类的加载
当程序要使用某个类时,如果该类还未被加载到内存中,则系统会通过加载,连接,初始化三步来实现对这个类进行初始化。

2.类加载器的组成

3.反射
JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。
要想解剖一个类,必须先要获取到该类的字节码文件对象。而解剖使用的就是Class类中的方法.所以先要获取到每一个字节码文件对应的Class类型的对象。

  1. 三种获取class方式
person p=new person();
Class a=p.getClass();
Class b=person.class;
Class c=Class.forName("cn.text.classdemo.person");
第三种必须全称

5.构造方法获取

Class c=Class.forName("cn.text.classdemo.person");
Constructor d=c.getConstructor();
Object p=d.newInstance();
Class c=Class.forName("cn.text.classdemo.person");
Constructor d=c.getConstructor(int.class,String.class);
此处以参数列表区别是那种构造方法
Object p=d.newInstance(30,"zhangsan");
System.out.println(p);
此种是获取构造器在获取对象实例
c.getConstructors()是获得构造方法的集合
--------------------------------
        Class c=Class.forName("cn.text.classdemo.person");
        Object p=c.newInstance();
        System.out.println(p);
简洁获得对象实例,不经过获取构造方法但是只能空参构造
所以前提是有空参构造
---------------------------------------------
        Class c=Class.forName("cn.text.classdemo.person");
        Constructor d=c.getDeclaredConstructor(String.class,int.class);
//      d.setAccessible(true);
        Object o=d.newInstance("zhangs",50);
        System.out.println(o);
这种获取全部构造方法,以参数列表区分
上面两种只能获得公共构造
getDeclaredConstructor获得全部包括private所以叫做暴力反射。
setAccessible参数true是忽略语言监测以获得全部权限方法

6.成员变量获取

        Class c = Class.forName("cn.text.classdemo.person");
        Object obj = c.newInstance();
        Field f = c.getField("age");
        f.set(obj, 30);set修改值并且需要对象支持
System.out.println(obj);
获取私有变量类似构造方法        

7.成员方法获取

        Class c = Class.forName("cn.text.classdemo.person");
        Object obj = c.newInstance(); 
        Method method=c.getMethod("run", int.class);
        method.invoke(obj, 5);
invoke运行方法,同样需呀对象支持
-----------------------------------------------------------
        ArrayList<String> a=new ArrayList<>();
        a.add("b");
        Class m=a.getClass();
        Method eMethod=m.getMethod("add", Object.class);
        eMethod.invoke(a, 10);
        System.out.println(a);
以上是将ArrayList<String>装入int通过反射获取add方法
---------------------------------------------------     
        FileReader fr=new FileReader("config.perpreties");
        Properties properties=new Properties();
        properties.load(fr);
        fr.close();
        String classname=properties.getProperty("classname");
        String methodname=properties.getProperty("methodname");
        Class c=Class .forName(classname);
        Object object=c.newInstance();
        c.getMethod(methodname).invoke(object);
此案例没有写对象,全部通过String获取增加灵活性
config.perpreties文件
#classname=cn.text.classdemo.person
#methodname=eat
#classname=cn.text.classdemo.Dog
#methodname=run
classname=cn.text.classdemo.Worker
methodname=work
上一篇 下一篇

猜你喜欢

热点阅读