反射調用private方法實踐(php、java)_php執行個體

來源:互聯網
上載者:User
單測中有個普遍性的問題,被側類中的private方法無法直接調用。小拽在處理過程中通過反射改變方法許可權,進行單測,分享一下,直接上代碼。

簡單被測試類別

產生一個簡單的被測試類別,只有個private方法。

複製代碼 代碼如下:
<?php/** * 崔小渙單測的基本模板。 * * @author cuihuan * @date 2015/11/12 22:15:31 * @version $Revision:1.0$ **/class MyClass {/** * 私人方法 * * @param $params * @return bool */private function privateFunc($params){if(!isset($params)){return false;}echo "test success";return $params;}}

單測代碼

複製代碼 代碼如下:
<?php/*************************************************************************** * * $Id: MyClassTest T,v 1.0 PsCaseTest cuihuan Exp$ * **************************************************************************//** * 崔小渙單測的基本模板。 * * @author cuihuan * @date 2015/11/12 22:09:31 * @version $Revision:1.0$ **/require_once ('./MyClass.php');class MyClassTest extends PHPUnit_Framework_TestCase {const CLASS_NAME = 'MyClass';const FAIL = 'fail';protected $objMyClass;/** * @brief setup: Sets up the fixture, for example, opens a network connection. * * 可以看做phpunit的建構函式 */public function setup() {date_default_timezone_set('PRC');$this->objMyClass = new MyClass();}/** * 利用反射,對類中的private 和 protect 方法進行單元測試 * * @param $strMethodName string :反射函數名 * @return ReflectionMethod obj :回調對象 */protected static function getPrivateMethod($strMethodName) {$objReflectClass = new ReflectionClass(self::CLASS_NAME);$method = $objReflectClass->getMethod($strMethodName);$method->setAccessible(true);return $method;}/** * @brief :測試private函數的調用 */public function testPrivateFunc(){$testCase = 'just a test string';// 反射該類$testFunc = self::getPrivateMethod('privateFunc');$res = $testFunc->invokeArgs($this->objMyClass, array($testCase));$this->assertEquals($testCase, $res);$this->expectOutputRegex('/success/i');// 捕獲沒有參數異常測試try { $testFunc->invokeArgs($this->transfer2Pscase, array());} catch (Exception $expected) {$this->assertNotNull($expected);return true;}$this->fail(self::FAIL);}}

運行結果

cuihuan:test cuixiaohuan$ phpunit MyClassTest.php PHPUnit 4.8.6 by Sebastian Bergmann and contributors.Time: 103 ms, Memory: 11.75MbOK (1 test, 3 assertions)

關鍵程式碼分析

封裝了一個,被測類方法的反射調用;同時,返回方法之前處理方法的接入許可權為true,便可以訪問private的函數方法。

複製代碼 代碼如下:
/** * 利用反射,對類中的private 和 protect 方法進行單元測試 * * @param $strMethodName string :反射函數名 * @return ReflectionMethod obj :回調對象 */protected static function getPrivateMethod($strMethodName) {$objReflectClass = new ReflectionClass(self::CLASS_NAME);$method = $objReflectClass->getMethod($strMethodName);$method->setAccessible(true);return $method;}

下面給大家分享java中利用反射調用另一類的private方法

我們知道,Java應用程式不能訪問持久化類的private方法,但Hibernate沒有這個限制,它能夠訪問各種層級的方法,如private, default, protected, public. Hibernate是如何?該功能的呢?答案是利用JAVA的反射機制,如下:

import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class ReflectDemo {  public static void main(String[] args) throws Exception {   Method method = PackageClazz.class.getDeclaredMethod("privilegedMethod", new Class[]{String.class,String.class});    method.setAccessible(true);   method.invoke(new PackageClazz(), "452345234","q31234132");  } } class PackageClazz {  private void privilegedMethod(String invokerName,String adb) {   System.out.println("---"+invokerName+"----"+adb);  } } 

輸出結果為:---452345234----q31234132

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.