Close

Java Reflection - Method.invoke() Examples

Java Reflection Java Java API 


Class:

java.lang.reflect.Method

java.lang.Objectjava.lang.Objectjava.lang.reflect.AccessibleObjectjava.lang.reflect.AccessibleObjectjava.lang.reflect.AnnotatedElementAnnotatedElementjava.lang.reflect.Executablejava.lang.reflect.Executablejava.lang.reflect.MemberMemberjava.lang.reflect.GenericDeclarationGenericDeclarationjava.lang.reflect.Methodjava.lang.reflect.MethodLogicBig

Method:

public Object invoke(Object obj,
                     Object... args)
              throws IllegalAccessException,
                     IllegalArgumentException,
                     InvocationTargetException

Invokes the underlying method represented by this Method object, on the specified object with the specified parameters.


Examples


package com.logicbig.example.method;

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

public class InvokeExample {

private static void process(String str) {
System.out.println("processing " + str);
}

public static void main(String... args) throws NoSuchMethodException,
InvocationTargetException, IllegalAccessException {
Method m = InvokeExample.class.getDeclaredMethod("process", String.class);
Object returnedValue = m.invoke(null, "test");
System.out.println(returnedValue);
}
}

Output

processing test
null




The instance method which also returns a String value:

package com.logicbig.example.method;

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

public class InvokeExample2 {
private String process(String str) {
System.out.println("processing " + str);
return "processing result";
}

public static void main(String... args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Method m = InvokeExample2.class.getDeclaredMethod("process", String.class);
Object returnedValue = m.invoke(new InvokeExample2(), "test");
System.out.println(returnedValue);
}
}

Output

processing test
processing result




Dynamic method dispatch is applied in case of instance method:

package com.logicbig.example.method;

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

public class InvokeExample3 {

private static class SuperTask {
protected void process() {
System.out.println("super class process");
}
}

private static class SpecializedTask extends SuperTask{
protected void process() {
System.out.println("sub class process");
}
}

public static void main(String... args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Method m = SuperTask.class.getDeclaredMethod("process");
m.invoke(new SpecializedTask());
}
}

Output

sub class process




See Also