调用java的私有方法

来源:互联网 发布:c语言中string.h 编辑:程序博客网 时间:2024/05/01 12:49
package base;
 
import java.lang.reflect.Method;
public class PrivateTestCall {
 
 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  try{
   //method one
   Method m=PrivateTest.class.getDeclaredMethod("print", new Class[]{});
   m.setAccessible(true);
   m.invoke(new PrivateTest(), new Object[]{});
   //method two
   PrivateTest privateTest=new PrivateTest();
   Method m1=privateTest.getClass().getMethod("print2", null);
   m1.setAccessible(true);
   m1.invoke(privateTest, null);
   //method three
   Method m2=PrivateTest.class.getMethod("print2", null);
   m2.setAccessible(true);
   m2.invoke(new PrivateTest(), null);
  }catch(Exception e){
   e.printStackTrace();
  }
 }
 
}

 

package base;
 
public class PrivateTest {
 private void print(){
  System.out.println("in private method");
 }
 public void print2(){
  System.out.println("in public method");
 }
}
原创粉丝点击