mercredi 7 février 2018

How to call method without parameter in java reflection

I wrote the following code with java reflection. In this code I call method1() which has a parameter and the code run without error. It's OK. But how can I call method2() and method3() which do not have parameters? How to call method without parameter in java reflection? Does Java support such feature?

import java.lang.reflect.Method;

class MethodCallTest {
  public static void main(String[] args) {
    MethodCallTest mct = new MethodCallTest();
    mct.start();
  }

  private void start(){
    try{
        Class<?> c = getClass();
          Method m1 = c.getDeclaredMethod("method1", String.class);
          m1.invoke(this, "method1");
    }catch(Exception e){
      e.printStackTrace();
    }
  }

  private void method1(String s){
    System.out.println("Hello from " + s);
  }

  private static void method2(){
    System.out.println("Hello from method2");
  }

  private static void method3(){
    System.out.println("Hello from method3");
  }

}





Aucun commentaire:

Enregistrer un commentaire