Java SE API

Method.invoke()

Invoke an accessible method; target failure is wrapped in InvocationTargetException. See official API for exceptions and overloads; Java 21-compatible example.

Formal Syntax & Structure

java syntaxjava
Object invoke(Object obj, Object... args)

Parameters & Attributes

NameTypeDescription
objObjectReceiver; ignored for static methods
argsObject...Invocation arguments

Return Value

Object

Invoke an accessible method; target failure is wrapped in InvocationTargetException.

Working Example

Example Snippetjava
import java.lang.annotation.*;import java.lang.reflect.*;import java.lang.invoke.*;import java.util.*;import java.nio.file.*;import java.nio.charset.StandardCharsets;import java.net.URLClassLoader;import java.net.URL;public class Main {    public static class Parent { public String name() { return "report"; } }    public static class Report extends Parent {        public int pages = 3;        private int secret = 7;        public String format(int count) { return "pages=" + count; }        public void reject() { throw new IllegalStateException("invalid"); }        public List<String> tags = List.of("daily");    }    public static void main(String[] args) throws Throwable {        Report report = new Report();        System.out.println(Report.class.getMethod("format", int.class).invoke(report, 2));        try { Report.class.getMethod("reject").invoke(report); } catch (InvocationTargetException e) { System.out.println(e.getCause().getClass().getSimpleName()); }    }}
Java Reference