反射

为什么要反射,反射的目的是为了什么???


基本方法

  1. Class.forName 获得类,&代表内部类,如下:
    final Class<?> globalClass = Class.forName("android.provider.Settings$Global");
  2. getFields() 获得类的变量,如下:
    final Field[] keys = globalClass.getFields();
  3. getMethod(方法名,方法参数);如下:
    final Method getString=globalClass.getMethod("getString", ContentProvider.class,String.class);
  • getMethod()和getDeclaredMethod()区别:getDeclaredMethod()获取的是类自身声明的所有方法,包含public、protected和private方法。getMethod()获取的是类的所有共有方法,这就包括自身的所有public方法,和从基类继承的、从接口实现的所有public方法。
  1. invoke(Object receiver, Object... args),第一个参数为类的实例,第二个参数为相应函数中的参数.如下:
    final Object value =getString.invoke(null,mContext.getContentResolver(),key.get(null));
  2. 获得类上的所有注解,如下:
    Method[] methods = MainActivity.class.getDeclaredMethods(); for (Method method : methods) { Annotation annotation = method.getAnnotation(MethodSafe.class); if(annotation!=null){ Log.e("lc", "" + method.toString()); } }
    MethodSafe.class 方法注解类,代码如下:
    `
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface MethodSafe {
    int num() default 0;
    String str() default "";
    boolean bool() default false;
    }

`

@Target:
说明了Annotation所修饰的对象范围:Annotation可被用于 packages、types(类、接口、枚举、Annotation类型)、类型成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch参数)。在Annotation类型的声明中使用了target可更加明晰其修饰的目标。

作用:用于描述注解的使用范围(即:被描述的注解可以用在什么地方)取值(ElementType)有:

  • CONSTRUCTOR:用于描述构造器
  • FIELD:用于描述域
  • LOCAL_VARIABLE:用于描述局部变量
  • METHOD:用于描述方法
  • PACKAGE:用于描述包
  • PARAMETER:用于描述参数
  • TYPE:用于描述类、接口(包括注解类型) 或enum声明

@Retention: 定义了该Annotation被保留的时间长短:某些Annotation仅出现在源代码中,而被编译器丢弃;而另一些却被编译在class文件中;编译在class文件中的Annotation可能会被虚拟机忽略,而另一些在class被装载时将被读取(请注意并不影响class的执行,因为Annotation与class在使用上是被分离的)。使用这个meta-Annotation可以对 Annotation的“生命周期”限制。

作用:表示需要在什么级别保存该注释信息,用于描述注解的生命周期(即:被描述的注解在什么范围内有效)
取值(RetentionPoicy)有:
1.SOURCE:在源文件中有效(即源文件保留)
2.CLASS:在class文件中有效(即class保留)
3.RUNTIME:在运行时有效(即运行时保留)


Ok,以上是基础知识,下面我们进入正题,为什么要使用反射呢?
A:反射就是为了拿拿不到的东西而已呀。但反射有一个问题就是以性能为代价,所以要尽量避免使用。


下面是获取崩溃堆栈中错误方法、注解,以及注解返回值的函数
`

/**
 * 保存崩溃堆栈中的错误方法
 * <p>
 * 保存策略:仅记录堆栈中第一个出错的主工程中的方法
 */
private static void saveStackTrace(Throwable ex) {
    StorgeUtil storgeUtil = new StorgeUtil(RunningEnvironment.sAppContext);
    MethodsStorage crashStackTrace = storgeUtil.get(MethodsStorage.class);
    if (crashStackTrace == null) {
        crashStackTrace = new MethodsStorage();
    }
    String methodFullName = "";
    String className = "";
    String methodName = "";
    String annotationMethod = "";
    String annotationReturnValue = "";
    
    StackTraceElement[] trace = ex.getStackTrace();
    if (trace == null || trace.length == 0) {
        return;
    }
    for (int i = 0; i < trace.length; i++) {
        className = trace[i].getClassName();
        methodName = trace[i].getMethodName();
        //以android开头都为系统方法,
        if (className.startsWith("android")) {
            break;
        }
        // 只记录project的packageName
        if (!className.startsWith(Context.getPackageName())) {
            continue;
        }
        methodFullName = className + File.separator + methodName;

    }
    if (TextUtils.isEmpty(methodFullName)) {
        if (ex.getCause() != null) {
            StackTraceElement[] causeTrace = ex.getCause().getStackTrace();
            if (causeTrace == null || causeTrace.length == 0) {
                return;
            }
            for (int i = 0; i < causeTrace.length; i++) {
                className = causeTrace[i].getClassName();
                methodName = causeTrace[i].getMethodName();
                if (className.startsWith("android")) {
                    break;
                }
                // 只记录project的packageName
                if (!className.startsWith(Context.getPackageName())) {
                    continue;
                }
                methodFullName = className + File.separator + methodName;
                break;
            }

        }
    }
    try {
        if (TextUtils.isEmpty(methodFullName)) {
            return;
        }
        Class clazz = Class.forName(className);
        try {
            Method catchMethod = clazz.getDeclaredMethod(methodName);
            //获得动态的annotation
            Annotation annotation = catchMethod.getAnnotation(MethodSafe.class);
            if (annotation != null) {
            //获得注解
                Method[] annotationMethods = annotation.annotationType().getDeclaredMethods();
                for (Method a : annotationMethods) {
                //通过返回值找到注解方法
                    if (catchMethod != null && catchMethod.getReturnType() != null && a.getReturnType().equals(catchMethod.getReturnType())) {
                        annotationMethod = a.getName();
                        break;
                    }
                }
                //通过注解方法名在注解类中找到注解返回值
                if (annotation.toString().contains(annotationMethod)) {
                    char[] annotationChars = annotation.toString().toCharArray();
                    char[] methodChars = annotationMethod.toCharArray();
                    for (int m = annotationChars.length - 1, n = methodChars.length - 1; m >= 0 && n >= 0; ) {
                        if (annotationChars[m] != methodChars[n]) {
                            m--;
                            n = methodChars.length - 1;
                        } else {
                            n--;
                            m--;
                            if (n == 0) {
                                if(m+methodChars.length<annotationChars.length){
                                annotationReturnValue = annotation.toString().substring(m + methodChars.length);}
                                break;
                            }
                        }
                    }

                    if (annotationReturnValue.length() > 1) {
                        char[] chars = annotationReturnValue.toCharArray();
                        boolean isFinished = false;
                        for (int k = 0; k < chars.length; k++) {
                            if (isFinished) {
                                break;
                            }
                            if (chars[k] == '=') {
                                for (int p = k + 1; p < chars.length; p++) {
                                    if (chars[p] == ',' || chars[p] == ')') {
                                        annotationReturnValue = annotationReturnValue.substring(k + 1, p);
                                        isFinished = true;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }

        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    crashStackTrace.className=className;
    crashStackTrace.methodName=methodName;
    crashStackTrace.annotationMethod=annotationMethod;
    crashStackTrace.annotationMethodValue=annotationReturnValue;
    storgeUtil.set(crashStackTrace, MethodsStorage.class);
}`
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容