Reflect method by class method name and parameters

import java.lang.reflect.Method;

public class Executor<T> {
	/**
	 *
	 * @param clazz class of the execution class
	 * @param str method name
	 * @param obj parameter
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public T getObject(Class clazz,String str,Object[] obj) throws Exception{
		Class[] cla=new Class[obj.length];
		if(obj.length==0){
			cla=null;
		}else{
			for(int i=0;i<obj.length;i++){
				cla[i]=obj[i].getClass();
			}
		}
		Method m=clazz.getMethod(str,cla);
		return (T)m.invoke(clazz.newInstance(), obj);
	}
	
	public static void main(String[] args) {
		try {
			new Executor<>().getObject(A.class, "printString",new Object[]{"string",1});
		} catch (Exception e) {
			e.printStackTrace ();
		}
	}
}

class A{
	public void printString(String str,Integer i){
		System.out.println(str+i);
	}
	
}


result:
string1

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327004471&siteId=291194637