2012-01-12 8 views

Respuesta

21

directamente desde el 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(); 
    } 
1
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; 
    } 
5

código a ejecutar método estático:

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

y clase con métodos estáticos:

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; 
    } 
} 
Cuestiones relacionadas