In Java, how to use reflection to get a static method and execute it?

directly from the interwebz

Class<?> class1;
    try {
        class1 = Class.forName(CLASS);
        Method method = class1.getMethod(METHOD, String.class);
        Object o = method.invoke(null, NAME);
        System.out.println(o);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }

Code to execute static method:

Method method = Utils.class.getMethod("generateCacheFolderName", Integer.class);
System.out.println(method.invoke(null, new Integer(10)));

and class with static method:

public class Utils {
    public static String generateCacheFolderName(Integer len) {
        Random rand = new Random();
        StringBuilder sb = new StringBuilder(len);

        for(int i = 0; i<len; ++i) 
            sb.append(rand.nextInt() % 10);

        return sb.toString();
    }

    public static String anotherStaticMethod() {

        return null;
    }
}

static public Object execute( Class<?> cls, Object instance, String methodname,
                             Object[] args, Class<?>[] types ) throws Exception {
        Object result = null;
        Method met = cls.getMethod( methodname, types );
        if (instance == null && !Modifier.isStatic( met.getModifiers() )) {
            throw new Exception("Method '" + methodname + "' is not static, so "
                                                + "instance must be not null");
        }
        try {
            result = met.invoke( instance, args );
        }
        catch (InvocationTargetException ite) {
            throw (Exception) ite.getCause();
        }
        return result;
    }

Tags:

Java