您的位置:首页 > 编程语言 > Java开发

调用java的私有方法

2006-08-08 01:00 399 查看
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");
 }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息