public class HelloWorld {
public static void main(String[] args) {
System.out.println("HelloWorld");
}
private void prt(String msg){
System.out.println(msg);
}
}
璋冪敤main鏂規(guī)硶濡備笅錛?br /> public class HelloWorldRefection {
public static void main(String[] args) throws InstantiationException, IllegalAccessException,
SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
Method method = HelloWorld.class.getMethod("main",String[].class);
method.invoke(null,(Object)new String[]{});
}
}
璋冪敤private鏂規(guī)硶濡備笅:
public class HelloWorldRefection {
public static void main(String[] args) throws InstantiationException, IllegalAccessException,
SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
Class clazz = HelloWorld.class;
HelloWorld helloworld = HelloWorld.class.newInstance();
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
System.out.println(method.getName());
if(method.getName().equals("prt")){
method.setAccessible(true);
method.invoke(helloworld, "hello");
}
}
}
}
鎬葷粨:
1 璋冪敤main鏂規(guī)硶闇瑕佹敞鎰忥紝main鏂規(guī)硶鐨勫弬鏁頒負String[]錛屼絾鏄湪method.invoke鏃訛紝闇瑕佸皢String[]寮哄埗杞崲涓篛bject錛岃嚦浜庡師鍥狅紝緗戜笂寰堝璇磋繖涓紝涓? 瑕佹槸璇磈dk鎵цmain鏂規(guī)硶鏃惰灝哠tring[]鍒嗘垚澶氫釜鍙傛暟絳夌瓑銆傚悗緇垜鍒嗘瀽浜嗘簮浠g爜鍚庯紝浼氬皢榪欎釜闂涓撻棬鍐欎釜鏂囩珷鍑烘潵銆?br /> 2 璋冪敤private鏂規(guī)硶闇瑕佹敞鎰忥紝鍦ㄨ皟鐢ㄦ鏂規(guī)硶涔嬪墠錛岄渶瑕佸皢姝ゆ墽琛岀殑鏂規(guī)硶璁劇疆浠ヤ笅錛岃屼笉鏄殢渚挎壘涓湴鏂硅繍琛屼笅method.setAccessible(true)灝卞畬浜嬩簡銆?br /> 3 浣跨敤鍙嶅皠鍔ㄦ佽皟鐢ㄦ柟娉曟椂錛屼富瑕佹槸鐢╩ethod.invoke()鏂規(guī)硶錛屽鏋滄槸闈欐佹柟娉曪紝鍒檌nvoke鐨勭涓涓弬鏁拌緗畁ull錛屽鏋滀笉鏄潤鎬佹柟娉曪紝鍒欏皢絎竴涓弬鏁拌 緗負璇ョ被鐢熸垚鐨勫璞″嵆鍙?img src ="http://www.aygfsteel.com/morgan/aggbug/387590.html" width = "1" height = "1" />
]]>