JAVA反射-根据某个对象的名称和方法去执行该方法

package com.citic.util;

import java.lang.reflect.*;
import java.util.HashMap;

import com.citic.util.comm.*;

/**
 * 根据某个对象的名称和方法去执行该方法
 * @author db2admin
 *
 */
public class ReflectUtil { 
    public static String methodName="execute";
    public static int debuglevel=8;
    public static HashMap<String,String[]> preexecute(String className,String xmlOder,String msgid){
        //返回有一般预设两个code,message
        return execute(className,"pre"+methodName,xmlOder,msgid);
    }
    
    public static HashMap<String,String[]> execute(String className,String xmlOder,String msgid){
        return execute(className,methodName,xmlOder,msgid);
    }
    
    @SuppressWarnings("unchecked")
    public static HashMap<String,String[]> execute(String className,String methodName,String xmlOder,String msgid) {
        HashMap<String,String[]> hm=new HashMap<String,String[]>();
        Method m1;
        Class<?> clazz;
        Object obj;
        String tb = ConfigFileUtil.getValue("SCHEMAPREFIX1")
                + ConfigFileUtil.getValue("T" + xmlOder);
        CommFun.log(debuglevel, "调用类:" + className + ",方法:" + methodName
                + ",参数:" + msgid+",表名:"+tb+",xmlOrder:"+xmlOder);
        try {
            if("".equals(tb)||tb==null){
                throw new Exception(xmlOder+"对应表名为空");
            }
            clazz=Class.forName(className);
            obj=clazz.newInstance();
            //解决父类调用问题
            while(true){
                try{
                    m1=obj.getClass().getDeclaredMethod(methodName, String.class,String.class,String.class);
                    CommFun.log(clazz.toString()+","+obj.toString()+","+m1.toString());
                }catch(NoSuchMethodException ne){
                    clazz=clazz.getSuperclass();
                    obj=clazz.newInstance();
                    CommFun.log(clazz.toString()+","+obj.toString());
                    continue;
                }
                break;
            }
            hm=(HashMap<String, String[]>) m1.invoke(obj,xmlOder,msgid,tb);
        } catch (Exception e) {
            CommFun.log("---------");
            e.printStackTrace();
            CommFun.log("["+e.toString()+"]");
        }
        return hm;
    }
}

 

上一篇:2020-04-13注解和反射


下一篇:idea抽取方法