Use reflection to invoke a private method

1. Create a Person class, write a few methods

seday18c Package Penalty for; 
/ ** 
 * @author xingsir 
 * create a Person class, write a few method 
 * / 
public class Person { 
	public void EAT () { 
		System.out.println ( "I am eating"); 
	} 
	public void RUN ( ) { 
		System.out.println ( "I run"); 
	} 
	// have added Private method for testing 
	Private void EAT (String name) { 
		System.out.println ( "I" + name + ", I eat "); 
	} 
	public void eAT (String name, int COUNT) { 
		System.out.println (" I "+ name +", I was eating "+ count +" bullfrogs "); 
	} 

}

  2. Use reflection to invoke a private method

seday18c Package; 

Import the java.lang.reflect.Method; 

/ ** 
* @author xingsir 
* using reflection to invoke the private method 
* / 
public class ReflectDemo5 { 

	public static void main (String [] args) throws Exception { 
          // static by Class forName method of loading the Person 
		class CLS = the Class.forName ( "seday18c.Person"); 
		// instantiate an object method 
		object cls.newInstance O = (); 
		/ * 
		 * class outside the encapsulation by reflection destroys the private calling method If it is not necessary to operate or design requirements, this is not recommended. 
		 * / 
		Method, m = cls.getDeclaredMethod ( "EAT", String.class); 
		// Set the access operation (without being given a direct call setting) before accessing the private methods 
		m.setAccessible (to true); 
        m.invoke (O, " Pig "); 
		
	} 

}

  

Guess you like

Origin www.cnblogs.com/xingsir/p/12667594.html