I have a bunch of static method names, how do I execute them. I think I can use reflection, but how to do that?
Asked
Active
Viewed 3.8k times
13
-
1just a note: static method isn't different from a regular method. invoking them is the same as invoking the regular methods through reflection – ligerdave Jan 12 '12 at 14:14
3 Answers
30
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();
}

hvgotcodes
- 118,147
- 33
- 203
- 236
8
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;
}
}

pbespechnyi
- 2,251
- 1
- 19
- 29
2
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;
}

Mr_and_Mrs_D
- 32,208
- 39
- 178
- 361

S.D.K
- 21
- 2