Invoking a method

suggest change

Using reflection, a method of an object can be invoked during runtime.

The example shows how to invoke the methods of a String object.

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

String s = "Hello World!";

// method without parameters
// invoke s.length()
Method method1 = String.class.getMethod("length");
int length = (int) method1.invoke(s); // variable length contains "12"

// method with parameters
// invoke s.substring(6)
Method method2 = String.class.getMethod("substring", int.class);
String substring = (String) method2.invoke(s, 6); // variable substring contains "World!"

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents