mardi 12 novembre 2019

Java reflection invoke method

I've defined this class that, when executed, it recovers all the methods from the class passes as a parameter to the main method and executes them all:

package tec;

import java.lang.reflect.Method;

public class LancerTests {
  static private void lancer(Class c) throws Exception{
    Method methods[] = c.getMethods();
    int nbTest = 0;
    for(Method m : methods){
      m.invoke(c.newInstance());
      System.out.println(".");
      nbTest++;
    }
    System.out.println("(" + nbTest + "):OK: " + c.getName());
  }

  static public void main(String[] args) throws Exception {
    boolean estMisAssertion = false;
    assert estMisAssertion = true;

    if (!estMisAssertion) {
      System.out.println("Execution impossible sans l'option -ea");
      return;
    }

    for(String arg : args){
      Class cls = Class.forName(arg);
      lancer(cls);
    }
  }
}

However, I'm getting the following error:

Exception in thread "main" java.lang.IllegalArgumentException: wrong number of arguments
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at tec.LancerTests.lancer(LancerTests.java:10)
    at tec.LancerTests.main(LancerTests.java:28)

I don't know what's wrong with the code.





Aucun commentaire:

Enregistrer un commentaire