Android中反射機(jī)制使用方法

前言

項(xiàng)目中有許多以前調(diào)用的API,Android studio提示已經(jīng)過(guò)時(shí),所以打算把過(guò)時(shí)的API替換掉也颤,但是新的API是@hide的,需要反射來(lái)調(diào)用郁轻,于是便重溫了一下反射機(jī)制翅娶。先上例子:wifi遺忘功能以前的實(shí)現(xiàn)方式是:

mWifiManager.removeNetwork(config.get(i).networkId);
mWifiManager.saveConfiguration();

但是新的實(shí)現(xiàn)方法是forget方法,由于forget方法是隱藏方法好唯,所以利用反射機(jī)制調(diào)用:

    public static void forgetNetwork(WifiManager manager, int networkId) {
        if (manager == null) {
            return;
        }
        try {
           //如果不傳入WiFimanager竭沫,我們可以利用Class類(lèi)來(lái)獲取
           // Class<WifiManager>  wifiManagerClass = WifiManager.class;
           //Method forget = wifiManagerClass.getDeclaredMethod("forget", int.class, Class.forName("android.net.wifi.WifiManager$ActionListener"));
            Method forget = manager.getClass().getDeclaredMethod("forget", int.class, Class.forName("android.net.wifi.WifiManager$ActionListener"));
            if (forget != null) {
                forget.setAccessible(true);
                forget.invoke(manager, networkId, null);
              //forget.invoke(wifiManagerClass.newInstance(), networkId, null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Android反射機(jī)制調(diào)用API步驟

Android反射機(jī)制調(diào)用API有三個(gè)步驟:
1.獲取Class對(duì)象

lass<WifiManager>  wifiManagerClass = WifiManager.class;

2.獲取方法

Method forget = wifiManagerClass.getDeclaredMethod("forget", int.class, Class.forName("android.net.wifi.WifiManager$ActionListener"));

3.方法調(diào)用

forget.invoke(manager, networkId, null);

獲取方法有g(shù)etMethod(String name, Class<?>[] parameterTypes, boolean recursivePublicMethods)和getDeclaredMethod(String name, Class<?>... parameterTypes).其中g(shù)etMethod獲取public方法,getDeclaredMethod方法獲取private方法渠啊。

獲取方法和方法調(diào)用源碼注釋

getDeclaredMethod源碼注釋如下:

    /**
     * Returns a {@code Method} object that reflects the specified
     * declared method of the class or interface represented by this
     * {@code Class} object. The {@code name} parameter is a
     * {@code String} that specifies the simple name of the desired
     * method, and the {@code parameterTypes} parameter is an array of
     * {@code Class} objects that identify the method's formal parameter
     * types, in declared order.  If more than one method with the same
     * parameter types is declared in a class, and one of these methods has a
     * return type that is more specific than any of the others, that method is
     * returned; otherwise one of the methods is chosen arbitrarily.  If the
     * name is "&lt;init&gt;"or "&lt;clinit&gt;" a {@code NoSuchMethodException}
     * is raised.
     *
     * <p> If this {@code Class} object represents an array type, then this
     * method does not find the {@code clone()} method.
     *
由源碼注釋可知输吏,第一個(gè)參數(shù)為方法名,后面的都是方法的參數(shù)替蛉,如果一個(gè)方法重載了多次贯溅,則根據(jù)參數(shù)匹配度來(lái)判斷是使用哪一個(gè)方法。
     * @param name the name of the method
     * @param parameterTypes the parameter array
     * @return  the {@code Method} object for the method of this class
     *          matching the specified name and parameters
     * @throws  NoSuchMethodException if a matching method is not found.
     * @throws  NullPointerException if {@code name} is {@code null}
     * @throws  SecurityException
     *          If a security manager, <i>s</i>, is present and any of the
     *          following conditions is met:
     *
     *          <ul>
     *
     *          <li> the caller's class loader is not the same as the
     *          class loader of this class and invocation of
     *          {@link SecurityManager#checkPermission
     *          s.checkPermission} method with
     *          {@code RuntimePermission("accessDeclaredMembers")}
     *          denies access to the declared method
     *
     *          <li> the caller's class loader is not the same as or an
     *          ancestor of the class loader for the current class and
     *          invocation of {@link SecurityManager#checkPackageAccess
     *          s.checkPackageAccess()} denies access to the package
     *          of this class
     *
     *          </ul>
     *
     * @jls 8.2 Class Members
     * @jls 8.4 Method Declarations
     * @since JDK1.1
     */
    @CallerSensitive
    public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
        throws NoSuchMethodException, SecurityException {
        return getMethod(name, parameterTypes, false);
    }

方法的調(diào)用invoke源碼注釋如下:

    /**   
     * Invokes the underlying method represented by this {@code Method}
     * object, on the specified object with the specified parameters.
     * Individual parameters are automatically unwrapped to match
     * primitive formal parameters, and both primitive and reference
     * parameters are subject to method invocation conversions as
     * necessary.
     *
     * <p>If the underlying method is static, then the specified {@code obj}
     * argument is ignored. It may be null.
     *
     * <p>If the number of formal parameters required by the underlying method is
     * 0, the supplied {@code args} array may be of length 0 or null.
     *
     * <p>If the underlying method is an instance method, it is invoked
     * using dynamic method lookup as documented in The Java Language
     * Specification, Second Edition, section 15.12.4.4; in particular,
     * overriding based on the runtime type of the target object will occur.
     *
     * <p>If the underlying method is static, the class that declared
     * the method is initialized if it has not already been initialized.
     *
     * <p>If the method completes normally, the value it returns is
     * returned to the caller of invoke; if the value has a primitive
     * type, it is first appropriately wrapped in an object. However,
     * if the value has the type of an array of a primitive type, the
     * elements of the array are <i>not</i> wrapped in objects; in
     * other words, an array of primitive type is returned.  If the
     * underlying method return type is void, the invocation returns
     * null.
     *
 由注釋可知第一個(gè)參數(shù)為調(diào)用該方法的實(shí)例對(duì)象躲查,其他參數(shù)為該方法的參數(shù)
     * @param obj  the object the underlying method is invoked from
     * @param args the arguments used for the method call
     * @return the result of dispatching the method represented by
     * this object on {@code obj} with parameters
     * {@code args}
     *
     * @exception IllegalAccessException    if this {@code Method} object
     *              is enforcing Java language access control and the underlying
     *              method is inaccessible.
     * @exception IllegalArgumentException  if the method is an
     *              instance method and the specified object argument
     *              is not an instance of the class or interface
     *              declaring the underlying method (or of a subclass
     *              or implementor thereof); if the number of actual
     *              and formal parameters differ; if an unwrapping
     *              conversion for primitive arguments fails; or if,
     *              after possible unwrapping, a parameter value
     *              cannot be converted to the corresponding formal
     *              parameter type by a method invocation conversion.
     * @exception InvocationTargetException if the underlying method
     *              throws an exception.
     * @exception NullPointerException      if the specified object is null
     *              and the method is an instance method.
     * @exception ExceptionInInitializerError if the initialization
     * provoked by this method fails.
     */
    @FastNative
    public native Object invoke(Object obj, Object... args)
            throws IllegalAccessException, IllegalArgumentException, InvocationTargetException;
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末它浅,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子镣煮,更是在濱河造成了極大的恐慌姐霍,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,427評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件典唇,死亡現(xiàn)場(chǎng)離奇詭異镊折,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)介衔,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,551評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)恨胚,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人炎咖,你說(shuō)我怎么就攤上這事赃泡『ǎ” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,747評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵升熊,是天一觀的道長(zhǎng)俄烁。 經(jīng)常有香客問(wèn)我,道長(zhǎng)级野,這世上最難降的妖魔是什么页屠? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,939評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮勺阐,結(jié)果婚禮上卷中,老公的妹妹穿的比我還像新娘。我一直安慰自己渊抽,他們只是感情好蟆豫,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,955評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著懒闷,像睡著了一般十减。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上愤估,一...
    開(kāi)封第一講書(shū)人閱讀 51,737評(píng)論 1 305
  • 那天帮辟,我揣著相機(jī)與錄音,去河邊找鬼玩焰。 笑死由驹,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的昔园。 我是一名探鬼主播蔓榄,決...
    沈念sama閱讀 40,448評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼默刚!你這毒婦竟也來(lái)了甥郑?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,352評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤荤西,失蹤者是張志新(化名)和其女友劉穎澜搅,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體邪锌,經(jīng)...
    沈念sama閱讀 45,834評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡勉躺,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,992評(píng)論 3 338
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了觅丰。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片饵溅。...
    茶點(diǎn)故事閱讀 40,133評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖舶胀,靈堂內(nèi)的尸體忽然破棺而出概说,到底是詐尸還是另有隱情,我是刑警寧澤嚣伐,帶...
    沈念sama閱讀 35,815評(píng)論 5 346
  • 正文 年R本政府宣布糖赔,位于F島的核電站,受9級(jí)特大地震影響轩端,放射性物質(zhì)發(fā)生泄漏放典。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,477評(píng)論 3 331
  • 文/蒙蒙 一基茵、第九天 我趴在偏房一處隱蔽的房頂上張望奋构。 院中可真熱鬧,春花似錦拱层、人聲如沸弥臼。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,022評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)径缅。三九已至,卻和暖如春烙肺,著一層夾襖步出監(jiān)牢的瞬間纳猪,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,147評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工桃笙, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留氏堤,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,398評(píng)論 3 373
  • 正文 我出身青樓搏明,卻偏偏與公主長(zhǎng)得像鼠锈,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子熏瞄,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,077評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容