import java.lang.reflect.Method;
public class Executor<T> {
/**
*
* @param clazz 执行类的class
* @param str 方法名
* @param obj 参数
* @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);
}
}
结果:
string1