class="java">import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class StrTest { public static void main(String args[]) { try { PrivateMethodClass a = new PrivateMethodClass(); Method m = PrivateMethodClass.class.getDeclaredMethod("print"); m.setAccessible(true); try { m.invoke(a); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } class PrivateMethodClass { private void print() { System.out.println("I am private method"); } }
?输出:I am private method.