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

Source: Internet
Author: User
Tags reflection

There is a universal problem in a single test, which cannot be directly invoked by the private method in the side class. Small drag in the process of reflection through the change of method authority, for a single test, share, directly on the code.

Simple Test class

To generate a simple tested class, there is only one private method.

Copy Code code as follows:

<?php/** * Chi Basic template for single measurement. * @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 Code code 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;/** * @brief setup:sets up the fixture, for example, opens a network connection. * * can be considered as PHPUnit constructor */public function Setup () {date_default_timezone_set (' PRC '); $this->objmyclass = new MyClass ();} /** * Use reflection to unit test the private and protect methods in a class * @param $strMethodName String: Reflection function Name * @return Reflectionmethod obj : Callback Object */protected static function Getprivatemethod ($strMethodName) {$objReflectClass = new Reflectionclass (self::class_ NAME); $method = $objReflectClass->getmethod ($strMethodName); $method->setaccessible(true); return $method;} /** * @brief: Test the invocation of the private function */public function 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 and Bergmann. time:103 MS, Memory:11.75mbok (1 Test, 3 assertions)

Critical Code Analysis

Encapsulates a reflection call to the method being measured, and access to the private function method is accessible when the access permission for the processing method is true before returning the method.

Copy Code code as follows:

/** * Use reflection to unit test the private and protect methods in a class * @param $strMethodName String: Reflection function Name * @return Reflectionmethod obj: Callback object/ protected static function Getprivatemethod ($strMethodName) {$objReflectClass = new Reflectionclass (self::class_name); $method = $objReflectClass->getmethod ($strMethodName); $method->setaccessible (true); return $method;}

Here's a private approach to using reflection to invoke another class in Java

We know that a Java application cannot access the private method of a persisted class, but Hibernate does not have this restriction to 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:

<span style= "FONT-SIZE:14PX;" >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)"; 
 } 
</span> 

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

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.