because the method out() is not a static method ,so it belongs to one instance of the class ,doesn't belong to the class. ms is one Class instance.you can call it by mds[i].invoke(ms.newInstance(),null); if you change the out() to a static method as following public static out(){ .....} then you can use : if(mds[i].getName() == "out") { mds[i].invoke(ms,null); }all the source code is following , package Test; import java.lang.reflect.*; public class MethodTest { public MethodTest() { } public static void main(String[] args) { MethodTest MethodTest1 = new MethodTest(); MethodTest1.run(); } public void run() { Class ms ; try { ms = Class.forName("Test.MS") ; Method[] mds = ms.getMethods() ; MS m = (MS)ms.newInstance() ; for (int i=0;i<mds.length ;i++) { System.out.println(""+i+":"+mds[i].getName() ); if (mds[i].getName().equals("out") ) { //由于out不是静态的,所以调用的时候必须有该类的实体 mds[i].invoke(m,null); } else if(mds[i].getName().equals("staticOut") ) { //由于staticOut是静态的,调用它可以使用Class对象,也可以使用该类的实体 mds[i].invoke(mds[i],null) ; mds[i].invoke(m,null); } } }catch(Exception ex) { ex.printStackTrace(); } } }
class MS { public MS() { } public void out() { System.out.println("MS out is invoked"); } static public void staticOut() { System.out.println("MS staticOut is invoked"); } } |