调用一个类的私有方法,java也提供了一些方法: 但是我们不需了解这个含有私有方法的类的内部实现。
测试用的类:
访问的方法:
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");
}
}
public class PrivateTest {
private void print(){
System.out.println("in private method");
}
public void print2(){
System.out.println("in public method");
}
}
访问的方法:
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();
}
}
}
结果:
in
private
method
in public method
in public method
in public method
in public method