Call a class method with 2 arguments in Java

Description

The following code shows how to call a class method with 2 arguments.

Example


//  w ww  .  j  a v a 2  s. co  m
import java.lang.reflect.Method;

public class Main {
  public static void main(String[] args) throws Exception {
    Class c = Class.forName("MyClass");
    Method m = c.getDeclaredMethod("say", new Class[] { String.class, String.class });
    Object i = c.newInstance();
    Object r = m.invoke(i, new Object[] { "Hello","World" });
  }
}

class MyClass {
  public void say(String s1, String s2) {
    System.out.println(s1 + " " + s2);
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Reflection »




Annotation
Array
Class
Constructor
Field
Generics
Interface
Method
Modifier
Package
Proxy