zoukankan      html  css  js  c++  java
  • 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); 
        } 
    }


  • 相关阅读:
    路飞学城Python-Day48
    路飞学城Python-Day46
    路飞学城Python-Day43
    路飞学城Python-Day42
    路飞学城Python-Day40(第四模块复习题)
    路飞学城Python-Day39(第四模块复习题)
    python小练习
    微信小程序常见错误及基本排除方法
    CSS文本样式
    小程序-广告轮播/控制属性
  • 原文地址:https://www.cnblogs.com/james1207/p/3370818.html
Copyright © 2011-2022 走看看