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

<dependencyManagement>
    <dependencies>
        <dependency>
            <!-- Import dependency management from Spring Boot -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>1.4.3.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

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
@Component("Server")
public class Server {
	@Autowired
    private ApplicationContext appContext;//Here we inject the spring app context for later use.

}
@Component("MethodsBean")
public class MethodsBean {
	public void aMethod() {
		System.out.println("test");
	}
}

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: