5

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

}
1
  • 2
    the second variable are vargs Commented Feb 7, 2018 at 8:31

1 Answer 1

10

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Ok, it works fine. I didn't know about vargs which can be ignored. I will accept this answer after 6 minutes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.