Java Reflexion basics. Get and execute methods

How to find and execute methods of an object using reflexion

Albert Lacambra BasilAlbert Lacambra Basil

Example class MyClass

package tech.lacambra.reflexion;

public class MyClass {
  private String str = "some value";
  public void methodA() {}
  private void privateMethodB() {}
  public String getStr() { return str; }
  public String getStr(String append) { return append + str; }

Get a method of a class

Method methodA = MyClass.class.getMethod("methodA");

Execute a method of a class

MyClass myClassInstance = new MyClass();

Get and execute a private method of a class

Method privateMethodB = MyClass.class.getDeclaredMethod("privateMethodB");

Execute a method with params

String result = (String) myClassInstance.getClass()
    .getMethod("getStr", String.class)
    .invoke(myClassInstance, "toAppend");

assertEquals("toAppendsome value", result);

Use a helper to get and assign returned values

public static <T> T getValue(String methodName, Object instance) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    return (T) instance.getClass().getMethod(methodName).invoke(instance);
String myString = getValue("getStr", new MyClass());