利用java反射机制调用类的public公有方法的例子

来源:互联网 发布:三菱plc编程软件fx 编辑:程序博客网 时间:2024/06/05 06:41

利用java反射机制调用类的public公有方法的例子:

代码如下:

package test;


import java.lang.reflect.Method;


/** 
* @author : suyuyuan
* @date :2016年5月20日 下午3:29:57 
* @version 1.0 
*/
public class MethodInvoke2 {
public static void main(String[] args) {


try {


Class cla = Class.forName("test.Out"); // 获得窗体类的Class对象

Method[] method = cla.getDeclaredMethods();// 


System.out.println("forName:" + cla);


for (Method me : method) {// 遍历该类方法的集合


System.out.println("方法有:" + me.toString());// 打印方法信息


}


Object obj = cla.newInstance(); 


Class[] classes = new Class[] {String.class};


Method methodSize = cla.getMethod("output", classes);


methodSize.invoke(obj, new Object[] {"成功!"});


 
} catch (Exception e) {


e.printStackTrace();


}


}
}


//



package test;
/** 
* @author : suyuyuan
* @date :2016年5月20日 下午4:15:12 
* @version 1.0 
*/
public class Out {
public void output(String str){

  System.out.println("调用output方法,输出信息:"+str);
  }


}

0 0