• 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;
        }
    }
  • 相关阅读:
    codeforces 1140D(区间dp/思维题)
    区间dp之四边形不等式优化详解及证明
    poj1947
    hdu4044
    poj1155
    poj3162(树形dp+优先队列)
    hdu4003详解(树形dp+多组背包)
    poj1947(树形背包)
    hdu1011(树形背包)(提供一个特殊样例)
    CopyOnWriteArrayList总结
  • 原文地址:https://www.cnblogs.com/tonggc1668/p/7477260.html
Copyright © 2020-2023  润新知