Java - Reflection Method Invoking

Introduction

You can invoke methods using reflection.

To invoke the setName() method of the Person class.

You can get the reference to the setName() method as

Class<Person> personClass = Person.class;
Method setName = personClass.getMethod("setName", String.class);

To invoke this method, call the invoke() method on the method's reference.

Demo

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

public class Main {
  public static void main(String[] args) {
    Class<Person> personClass = Person.class;
    try {// w  ww  .j  ava2  s  .  co  m
      // Create an object of Person class
      Person p = personClass.newInstance();
      System.out.println(p);

      // Get the reference of the setName() method
      Method setName = personClass.getMethod("setName", String.class);

      // Invoke the setName() method on p passing a new value for name
      setName.invoke(p, "book2s.com");
      System.out.println(p);
    } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException
        | IllegalArgumentException | InvocationTargetException e) {
      System.out.println(e.getMessage());
    }
  }
}

class Person {
  private int id = -1;
  private String name = "Unknown";

  public Person() {
  }

  public Person(int id, String name) {
    this.id = id;
    this.name = name;
  }

  public int getId() {
    return id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String toString() {
    return "Person: id=" + this.id + ", name=" + this.name;
  }
}

Result