Here you can find the source of invokeStaticMethod(Class> cls, String method, Class>[] params, Object... args)
Parameter | Description |
---|---|
cls | The class of the static method |
method | The name of the method to invoke |
public static Object invokeStaticMethod(Class<?> cls, String method, Class<?>[] params, Object... args)
//package com.java2s; //License from project: Open Source License import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Main { /**/* www . j a va 2s .co m*/ * Invokes a static method * @param cls The class of the static method * @param method The name of the method to invoke * @return The result of the method */ public static Object invokeStaticMethod(Class<?> cls, String method, Class<?>[] params, Object... args) { try { return getMethod(cls, method, params).invoke(null, args); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return null; } /** * Retrieves a method * * @param cl The class to retrieve the method from * @param method The name of the method * @param args The argument types that the method should have * @return null if no method was found */ public static Method getMethod(Class<?> cl, String method, Class<?>[] params) { for (Method m : cl.getDeclaredMethods()) { if (m.getName().equals(method) && classListEqual(params, m.getParameterTypes())) { m.setAccessible(true); return m; } } if (cl.getSuperclass() != null) return getMethod(cl.getSuperclass(), method, params); return null; } /** * Retrieves a method * * @param cl The class to retrieve the method from * @param method The name of the method * @return null if no method was found */ public static Method getMethod(Class<?> cl, String method) { for (Method m : cl.getDeclaredMethods()) { if (m.getName().equals(method)) { m.setAccessible(true); return m; } } if (cl.getSuperclass() != null) return getMethod(cl.getSuperclass(), method); return null; } private static boolean classListEqual(Class<?>[] l1, Class<?>[] l2) { boolean equal = true; if (l1.length != l2.length) { return false; } for (int i = 0; i < l1.length; i++) { if (l1[i] != l2[i]) { return false; } } return equal; } }