Android & Java 反射基本知识讲解

反射的原理

反射大家用起来很方便,由于性能其实也比较不错了,因此用得挺广的,我们通常这么用反射

Method method = XXX.class.getDeclaredMethod(xx,xx);
method.invoke(target,params)

Java 的反射机制的实现要借助于4个类:class,Constructor,Field,Method;其中class代表的时类对 象,Constructor-类的构造器对象,Field-类的属性对象,Method-类的方法对象。

不过这里我不准备用大量的代码来描述其原理,而是讲几个关键的东西,然后将他们串起来

获取Method

要调用首先要获取Method,而获取Method的逻辑是通过Class这个类来的,而关键的几个方法和属性如下:

-------Class.java------------
public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
        throws NoSuchMethodException, SecurityException {
        return getMethod(name, parameterTypes, false);
    }

public Method[] getDeclaredMethods() throws SecurityException {
        Method[] result = getDeclaredMethodsUnchecked(false);
        for (Method m : result) {
            // Throw NoClassDefFoundError if types cannot be resolved.
            m.getReturnType();
            m.getParameterTypes();
        }
        return result;
    }

反射详细步骤

1.拿到类名

String className = Tool.class.getName();

这时候拿到的就是“com.example.test.Tool”
2.根据类包名拿到Class

Class toolClass = Class.forName(className);

3.根据Class拿到实例Object

Object obj = toolClass.newInstance();

然后强制转换就可以了。
当然也可以一句代码解决:

Tool t = (Tool) Class.forname(className).newInstance();

通过Tool类遍历到所有的构造方法、public(方法、字段),private(方法、字段),protect(方法、字段)。

 Method m = t.getMethod("方法名", new Class[] {
                byte[].class, byte[].class, int.class });
        Object s = m.invoke(SmsManager.getDefault(), null, pdu, 1);

先简单说到这里,有什么不对的地方欢迎指出,之后继续更新深层次的理解。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章