Reflection calls Private method Practice (PHP, Java) _php instances

Source: Internet
Author: User
There is a universal problem in the single measurement, which cannot be called directly by the private method in the side class. Small drag in the process through reflection to change the method permissions, the single test, share, directly on the code.

Simple Test class

Generate a simple tested class with only a private method.

Copy the Code code as follows:
<?php/** * Chi Basic template for single test. * * @author Cuihuan * @date 2015/11/12 22:15:31 * @version $Revision: 1.0$ **/class MyClass {/** * Private method * * @param $params * @return bool */private function Privatefunc ($params) {if (!isset ($params)) {return false;} echo "Test Success"; return $params;}}

Single Test Code

Copy CodeThe code is as follows:
<?php/*************************************************************************** * * $Id: MyClassTest T,v 1.0 Pscasetest Cuihuan exp$ * **************************************************************************//** * Chi Basic template for single measurement. * * @author Cuihuan * @date 2015/11/12 22:09:31 * @version $Revision: 1.0$ **/require_once ('./myclass.php '); class Myclasst EST extends phpunit_framework_testcase {const CLASS_NAME = ' MyClass '; const FAIL = ' FAIL ';p rotected $objMyClass;/** * @brie F Setup:sets up the fixture, for example, opens a network connection. * * can be seen as PHPUnit constructor */public function Setup () {date_default_timezone_set (' PRC '); $this->objmyclass = new MyClass ();} /** * unit testing of private and protect methods in classes using reflection * * @param $strMethodName String: Reflection function Name * @return Reflectionmethod obj: Callback Object */p rotected static function Getprivatemethod ($strMethodName) {$objReflectClass = new Reflectionclass (self::class_name); $ method = $objReflectClass->getmethod ($strMethodName); $method->setaccessible (true); return $method;} /** * @brief: The call to the private function is tested */public functions Testprivatefunc () {$testCase = ' just a test string ';//reflect the class $testfunc = self: : Getprivatemethod (' Privatefunc '); $res = $testFunc->invokeargs ($this->objmyclass, Array ($testCase)); $this- >assertequals ($testCase, $res); $this->expectoutputregex ('/success/i ');//capture no parameter exception test try {$testFunc Invokeargs ($this->transfer2pscase, Array ());} catch (Exception $expected) {$this->assertnotnull ($expected); return true;} $this->fail (Self::fail);}}

Run results

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)

Critical Code Analysis

Encapsulates a reflection invocation of a method that is being measured, and then accesses the private function method if the access permission for the method before the method is returned is true.

Copy the Code code as follows:
/** * unit testing of private and protect methods in classes using reflection * * @param $strMethodName String: Reflection function Name * @return Reflectionmethod obj: Callback Object */p rotected static function Getprivatemethod ($strMethodName) {$objReflectClass = new Reflectionclass (self::class_name); $ method = $objReflectClass->getmethod ($strMethodName); $method->setaccessible (true); return $method;}

Now let's share the private method in Java that uses reflection to call another class

We know that Java applications cannot access the private method of a persisted class, but Hibernate does not have this restriction and it can access various levels of methods, such as private, default, protected, public. How does hibernate implement this function? The answer is to use the Java reflection mechanism, as follows:

Import java.lang.reflect.InvocationTargetException; Import Java.lang.reflect.Method; public class Reflectdemo {public  static void Main (string[] args) throws Exception {   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);  } }

The output is:---452345234----q31234132

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    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.