简单的反射

核心代码

File codeDir = getDir("dex",Context.MODE_PRIVATE);

DexClassLoader classLoader = new DexClassLoader(path, codeDir.getAbsolutePath(),
            null,
            this.getClass().getClassLoader());
    try {
        Class clazz = classLoader.loadClass("zhao.com.javabean.Student");
        Constructor constructor = clazz.getDeclaredConstructor();//如果是私有构造方法
        constructor.setAccessible(true);
        Object obj = constructor.newInstance();

        //Object obj = clazz.newInstance();//不是私有构造方法
        //Method setAge = clazz.getMethod("setAge", int.class);//public set方法
        //setAge.invoke(obj,20);
        //Method age = clazz.getDeclaredMethod("getAge"); //private get方法
        //age.setAccessible(true);//将Accessible设置为true
        //int ageNum = (int) age.invoke(obj);
        //Toast.makeText(this, ""+ageNum, Toast.LENGTH_SHORT).show();


        Method sumGrade = clazz.getMethod("sumGrade", double.class,double.class,double.class);
        
        double sum = (double) sumGrade.invoke(obj,100,80,60);
        Field field = clazz.getDeclaredField("grade"); //属性
        field.setAccessible(true);
        double grade = (double) field.get(obj);

        Toast.makeText(this, "grade:"+grade+",sumGrade:"+sum, Toast.LENGTH_SHORT).show();

你可能感兴趣的:(进阶,简单反射)