Practice of calling private methods through reflection: php and java

Source: Internet
Author: User
: This article describes how to call the private method through reflection in php and java. if you are interested in the PHP Tutorial, refer to it. 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

The above introduces the practice of calling private methods through reflection in php and java, including some content. I hope to help some friends who are interested in PHP tutorials.

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.