SpringBoot java reflection example

If you want to call a method in a spring bean, and the method’s name is unknown, you should use java reflection to call the method.

1. Pom.xml

Here we use spring boot 1.4.3

            <!-- Import dependency management from Spring Boot -->

2. Define two spring beans

Here we define two beans:

  • The first bean is the server bean, which would call the second bean’s method by reflection
  • The second bean is the bean to be called by the server bean, supply some methods to be called
public class Server {
    private ApplicationContext appContext;//Here we inject the spring app context for later use.

public class MethodsBean {
	public void aMethod() {

3. Use java reflection to call the MethodsBean’s any method

Now it’s the trick:

String methodName = "aMethod"; // the method to be called

Object bean = appContext.getBean("MethodsBean");//defined by the @Component params

Method method = bean.getClass().getMethod(methodName);
if (method != null) {
    return (Integer) method.invoke(bean);//java reflection here.

} else {
    //print error message.


The core steps are as follows:

  • use appContext to get the bean object
  • use methodName as the param to search for the Method object
  • if got the method object, then use java reflection to invoke the method

You can find detail documents about the springboot and java reflection here: