Practice of calling private methods through reflection (php, java), _ PHP Tutorial

Source: Internet
Author: User
Reflection calls private method practices (php, java ),. The practice of calling private methods through reflection (php and java) has a common problem during a single test. private methods in the side class cannot be called directly. In the processing process, Xiao Yan changes the method weight reflection and calls the private method (php, java ),

There is a general problem in a single test, and the private method in the side class cannot be called directly. During the process, Xiao Yan reflected and changed the method permission to perform a single test, shared it, and directly added the code.

Simple tested class

Generate a simple tested class with only one private method.

The code is as follows:
<? Php/*** basic template of Cui Xiaoyu single test. ** @ Author cuihuan * @ date 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

The code is as follows:
<? Php /************************************** ************************************* $ id: myClassTest T, v 1.0 PsCaseTest cuihuan Exp $ ********************************** **************************************** * // *** basic template of Cui Xiaoyu single test. ** @ Author cuihuan * @ date 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. ** constructor of phpunit */public function setup () {date_default_timezone_set ('prc'); $ this-> objMyClass = new MyClass ();} /*** use reflection to perform unit tests on the private and protect methods in the 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: Call the test private function */public function testPrivateFunc () {$ testCase = 'just a test string'; // reflection class $ testFunc = self: getPrivateMethod ('privatefunc '); $ res = $ testFunc-> invokeArgs ($ this-> objMyClass, array ($ testCase); $ this-> assertEquals ($ testCase, $ res ); $ this-> expectOutputRegex ('/success/I'); // catch no parameter exception test try {$ testFunc-> invokeArgs ($ this-> transfer2Pscase, array ();} catch (Exception $ expected) {$ this-> assertNotNull ($ expected); return true ;}$ this-> fail (self :: FAIL );}}

Running result

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

Key code analysis

Encapsulate a reflection call of the method to be tested. at the same time, if the access permission of the method before returning the method is true, you can access the private function method.

The code is as follows:
/*** Use reflection to perform unit tests on the private and protect methods in the 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 ;}

The following is an example of calling another type of private method using reflection in java.

We know that Java applications cannot access the private method of persistence classes, but Hibernate does not have this restriction. it can access various levels of methods, such as private, default, protected, and public. how does Hibernate implement this function? The answer is to use the reflection mechanism of JAVA, as shown below:

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);  } } 

Output result: --- 452345234 ---- q31234132

Articles you may be interested in:
  • Analysis on private property inheritance in php
  • Questions about private access control in PHP classes and objects
  • Differences between public, private, and protected in php class and instance analysis
  • Analysis on php object-oriented public private protected access modifier
  • Is the private modifier in Java invalid?

Callback (php, java) has a general problem in a single test. private methods in the side class cannot be called directly. In the processing process, drag the method right through reflection...

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.