zoukankan      html  css  js  c++  java
  • 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;
        }
    }
  • 相关阅读:
    在线工具TOOL收藏
    HtmlDocument [代码碎片笔记]
    ChromiumWebBrowser [链接]
    PHP [开发汇总]
    Discuz[技术文献]
    [jvm] -- 监控和调优常用命令工具篇
    [jvm] -- 常用内存参数配置篇
    [日常摘要] -- 事务的隔离级别篇
    [日常摘要] -- ThreadLocal篇
    [日常摘要] -- zookeeper篇
  • 原文地址:https://www.cnblogs.com/tonggc1668/p/7477260.html
Copyright © 2011-2022 走看看