Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
  }

}
like image 243
Nyein Chan Avatar asked Dec 24 '22 10:12

Nyein Chan


1 Answers

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);
like image 123
Peter Lawrey Avatar answered Jan 16 '23 03:01

Peter Lawrey