call Static Method - Java Reflection

Java examples for Reflection:Method

Description

call Static Method

Demo Code


//package com.java2s;

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

public class Main {
    private static HashMap<String, Method> sMethodCache = new HashMap<String, Method>();
    private static HashMap<Class<?>, Class<?>> primativeClassMap = new HashMap<Class<?>, Class<?>>();

    public static Object callStaticMethod(Class<?> clazz,
            String methodName, Object... args) {
        Object result = null;/*from ww  w .  j  a  v a2s .  c  o  m*/
        try {
            Method method = getMethodBestMatch(clazz, methodName,
                    getArgsTypes(args));
            result = method.invoke(clazz, args);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return result;
    }

    private static Method getMethodBestMatch(Class<?> clazz,
            String methodName, Class<?>... argClasses) throws Throwable {
        String methodFullName = genMethodFullName(clazz, methodName,
                argClasses);
        if (sMethodCache.containsKey(methodFullName))
            return sMethodCache.get(methodFullName);
        for (Method method : clazz.getDeclaredMethods()) {
            if (method.getName().equals(methodName)) {
                Class<?>[] tmpArgs = method.getParameterTypes();
                if (compareArgs(tmpArgs, argClasses)) {
                    method.setAccessible(true);
                    sMethodCache.put(methodFullName, method);
                    return method;
                }
            }
        }
        String msg = "";
        for (Class<?> cls : argClasses) {
            msg += cls.getSimpleName() + ",";
        }
        msg = "Can't get method: " + clazz.getSimpleName() + "."
                + methodName + "(" + msg + ")";
        throw new Exception(msg);
    }

    private static Class<?>[] getArgsTypes(Object... args) {
        Class<?>[] argClasses = new Class<?>[args.length];
        for (int i = 0; i < args.length; i++) {
            argClasses[i] = (args[i] != null) ? args[i].getClass() : null;
            i++;
        }
        return argClasses;
    }

    private static String genMethodFullName(Class<?> clazz,
            String methodName, Class<?>... argClasses) {
        StringBuilder name = new StringBuilder();
        name.append(clazz.getName());
        name.append(":");
        name.append(methodName);
        for (int i = 0; i < argClasses.length; i++) {
            if (i == (argClasses.length - 1)) {
                name.append(argClasses[i].getName());
            } else {
                name.append(argClasses[i].getName());
                name.append(",");
            }
        }
        return name.toString();
    }

    private static boolean compareArgs(Class<?>[] dstArgs,
            Class<?>[] origArgs) {
        if (dstArgs.length != origArgs.length)
            return false;
        for (int i = 0; i < dstArgs.length; i++) {
            if (!isChildClass(dstArgs[i], origArgs[i]))
                return false;
        }
        return true;
    }

    public static Class<?> getClass(String className) {
        Class<?> clazz = null;
        try {
            clazz = Class.forName(className);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return clazz;
    }

    public static Class<?> getClass(String className,
            boolean shouldInitialize, ClassLoader classLoader) {
        Class<?> clazz = null;
        try {
            clazz = Class.forName(className, shouldInitialize, classLoader);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return clazz;
    }

    private static boolean isChildClass(Class<?> origClass,
            Class<?> dstClass) {
        if (dstClass == null)
            return true;
        if (origClass.isInterface()) {
            for (Class<?> i : dstClass.getInterfaces()) {
                if (origClass == i)
                    return true;
            }
        }
        if (origClass.isPrimitive()
                && (primativeClassMap.get(origClass) == dstClass))
            return true;
        for (; dstClass != Object.class; dstClass = dstClass
                .getSuperclass()) {
            if (dstClass == origClass)
                return true;
        }
        return false;
    }
}

Related Tutorials