• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
james1207

博客园    首页    新随笔    联系   管理    订阅  订阅

java通过反射调用不同参数的方法

import java.lang.reflect.Method;


public class testReflect {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			Wu w=new Wu();
			Object[] argspara=new Object[]{};
			testReflect.invokeMethod(w, "outInfo",argspara);
			argspara=new Object[]{"wu"};
			testReflect.invokeMethod(w, "outInfo",argspara);
			argspara=new Object[]{"wu",2};
			testReflect.invokeMethod(w, "outInfo",argspara);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 反射调用方法
	 * @param newObj 实例化的一个对象
	 * @param methodName 对象的方法名
	 * @param args 参数数组
	 * @return 返回值
	 * @throws Exception
	 */
	public static Object invokeMethod(Object newObj, String methodName, Object[] args)throws Exception {
		Class ownerClass = newObj.getClass();
		Class[] argsClass = new Class[args.length];
		for (int i = 0, j = args.length; i < j; i++) {
		   argsClass[i] = args[i].getClass();
		}
		Method method = ownerClass.getMethod(methodName, argsClass);
		return method.invoke(newObj, args);
	}
}

class Wu{ 
    public void outInfo() { 
        System.out.println("Wu.outInfo"); 
    } 
    public void outInfo(String s) { 
        System.out.println("Wu.outInfo(String s):"+s); 
    } 
    public void outInfo(String s,Integer n) { 
        System.out.println("Wu.outInfo(String s,int n):"+s+n); 
    } 
}


posted @ 2013-10-15 18:38  Class Xman  阅读(1017)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3