• ReflectionUtil


    import java.lang.reflect.Method;
    
    
    @SuppressWarnings("rawtypes")
    public class ReflectionUtil {
        @SuppressWarnings("unchecked")
        public static Object invokeStaticMethod(String className, String methodName, Object[] args) throws Exception {
            Class ownerClass = Class.forName(className);
    
            Method tMethod = null;
            tMethod = getMethod(ownerClass, methodName, args);
            if (tMethod == null) {
                Class[] argsClass = new Class[args.length];
                int i = 0;
                for (int j = args.length; i < j; i++) {
                    argsClass[i] = args[i].getClass();
                }
                tMethod = ownerClass.getMethod(methodName, argsClass);
            }
            return tMethod.invoke(null, args);
        }
        
        /***
         * reflection invoke method
         * @param className
         * @param methodName
         * @param args
         * @return
         * @throws Exception
         */
        @SuppressWarnings("unchecked")
        public static Object invokeMethod(String className, String methodName, Object[] args) throws Exception {
            Class ownerClass = Class.forName(className);
            Method tMethod = null;
            
            tMethod = getMethod(ownerClass, methodName, args);
            if (tMethod == null) {
                Class[] argsClass = new Class[args.length];
                int i = 0;
                for (int j = args.length; i < j; i++) {
                    argsClass[i] = args[i].getClass();
                }
                tMethod = ownerClass.getMethod(methodName, argsClass);
            }
            return tMethod.invoke(ownerClass.newInstance(), args);
        }
    
        private static Method getMethod(Class clazz, String methodName, Object[] args) {
            Method[] methods = clazz.getMethods();
            Method m = null;
            for (Method method : methods) {
                if (method.getName().equals(methodName)) {
                    Class[] parameterTypes = method.getParameterTypes();
                    if (method.getParameterTypes().length == args.length) {
                        for (int i = 0; i < parameterTypes.length; i++) {
                            if (! parameterTypes[i].isInstance(args[i])) {
                                break;
                            }
                            m = method;
                        }
                    }
                }
            }
            return m;
        }
    }
  • 相关阅读:
    基于XML的声明式事务控制
    spring中JdbcTemplate使用
    四种常用的通知类型(xml)
    AOP配置步骤(XML)
    12388. 图论割边
    12389. 割点
    12206. 电缆网络
    12178. 破坏牛棚
    java反射笔记
    java单元测试
  • 原文地址:https://www.cnblogs.com/tonggc1668/p/7477260.html
Copyright © 2020-2023  润新知