天天看點

Android——反射Reflect機制運用簡單介紹擷取Class對象通過反射調用私有方法通過反射操作私有屬性奉上一個調用反射的幫助類

簡單介紹

java的反射機制使java成為一種動态語言,通過反射機制能夠在運作時或的一個對象的所有資訊,包括他的包名,它的所有方法和成員變量。當然知道包名可以直接取得該類,進而獲得他的執行個體。

擷取Class對象

//通過對象獲得:
class = b.getClass();

//通過完整包類名獲得:
class = Class.fromName("包名.類名")

//本包可以通過.class獲得:
class = 類名.class
           

通過反射調用私有方法

//獲得類
Class<?> c1 = persen.getClass();
try {
    //通過方法名獲得方法,這是私有方法
    Method method1 = c1.getDeclaredMethod("method1");
    //調用方法私有方法的關鍵
    method1.setAccessible(true); //設定該私有方法可被調用
    //方法調用
    method1.invoke(c1.newInstance());

    //這是帶參數的方法,需要在獲得方法的時候把參數的類型都加上
    Method method2 = c1.getDeclaredMethod("method2",String.class);
    //調用方法,填寫參數
    method2.invoke(c1.newInstance(),"kk");

    //這是有傳回值的方法
    Method method3 = c1.getDeclaredMethod("method3");
    return (int) method3.invoke(c1.newInstance());
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) {
    e.printStackTrace();
}
           

通過反射操作私有屬性

Class c1 = persen.getClass();
try {
    //通過屬性名獲得屬性
    Field name = c1.getDeclaredField("name");
    //由于是私有屬性,是以需要設定它可見
    name.setAccessible(true);
    //直接修改該對象的該屬性的值
    name.set(persen,"小明");
    //獲得該對象的該屬性的值
    return (String) name.get(persen);
} catch (NoSuchFieldException e) {
    e.printStackTrace();
} catch (IllegalAccessException e) {
    e.printStackTrace();
}
           

奉上一個調用反射的幫助類

public class ReflectUtils {

  public static Method getMethod(@NonNull Class<?> clazz, @NonNull String methodName) throws NoSuchMethodException {
    Method method = clazz.getDeclaredMethod(methodName);
    method.setAccessible(true);
    return method;
  }

  public static void invokeMethod(@NonNull Class<?> clazz, @NonNull String methodName) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException {
    getMethod(clazz, methodName).invoke(clazz.newInstance());
  }

  public static Field getVariable(@NonNull Class<?> clazz, @NonNull String variableName) throws NoSuchFieldException {
    Field variable = clazz.getDeclaredField(variableName);
    variable.setAccessible(true);
    return variable;
  }
}