Package COM. hsj; import Java. lang. reflect. method; import Org. JUnit. test;/*** note: the student class inherits the person class. If the student class rewrites the Eat method, the student class's eat method is called to obtain the person's protected Method Using Reflection. * knowledge point: use the related methods of the Class Object to obtain the protected methods of the parent class **/public class extendsreflect {@ testpublic void test () {try {/*** use class. forname () obtains the bytecode object equivalent to strudent. class (), student. getclass () * student is the Instance Object of student */class clazz = Class. forname ("com. hsj. domain. student "); method met Hod = NULL; while (true) {try {// obtain the Eat method. If the Eat method is obtained, we end the loop. Otherwise, the corresponding method of the bytecode object of the parent class is recursively called, if the bytecode object is an object, exit the loop method = clazz. getdeclaredmethod ("eat", null); break;} catch (nosuchmethodexception e) {If (clazz = object. class) {system. out. println ("no corresponding method"); break;}/*** this code is used to obtain the bytecode object of the parent class */clazz = clazz. getsuperclass () ;}}/*** if the corresponding method is found */If (method! = NULL) {If (! Method. isaccessible () {method. setaccessible (true);} method. invoke (clazz. newinstance (), null) ;}} catch (exception e) {e. printstacktrace ();}}}
Package COM. hsj. domain; public class student extends person {public void learn () {system. out. println ("student's learning method") ;}@ overrideprotected void eat () {system. out. println ("overwritten eat method ");}}
Package COM. hsj. domain; public class person {private string username; private string password; Public Person (string username, string password) {super (); this. username = username; this. password = password;} public person () {super ();} Public String GetUserName () {return username;} public void setusername (string username) {This. username = username;} Public String GetPassword () {return password;} public void set Password (string password) {This. Password = password;} public static void main (string [] ARGs) {If (ARGs! = NULL) {for (string S: ARGs) {system. out. println (s) ;}} system. out. println ("Reflection main function test");} public void test1 (char [] chars) {system. out. println ("test1 char []");} public void Test2 (integer [] ints) {system. out. println ("test2... ");} public void test3 (string S1, string S2) {system. out. println ("test3") ;}@ overridepublic string tostring () {return this. username + ":" + this. password;} protected void eat () {system. out. println ("protected method eat .... ");}