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");
  }
}
                How to call method without parameter in java reflection?
Don't give it an argument if it doesn't expect one.
Does Java support such feature?
Yes.
Method m2 = c.getDeclaredMethod("method2");
m2.invoke(this);
or
c.getDeclaredMethod("method2").invoke(this);
BTW Technically this is the first implicit argument.  If you have no arguments the method has to be static which is called like this.
static void staticMethod() { }
called using
c.getDeclaredMethod("staticMethod").invoke(null);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With