反射

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


基本方法

  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);
}`
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容