調用一個類的私有方法,java也提供了一些方法: 但是我們不需了解這個含有私有方法的類的內部實現。
測試用的類:
package base;

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
測試用的類:


















訪問的方法:












































結果:



