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

I have a bunch of static method names on how to execute them. I think I can use reflection, but how to do it?

+6
source share
3 answers

directly from 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(); } 
+21
source

Code to execute the 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 otherStaticMethod() { return null; } } 
+5
source
 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; } 
+1
source

Source: https://habr.com/ru/post/905825/


All Articles