Skip to content

Java reflection example

Introduction

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. This post will guide you through the process of setting up a Spring Boot project and using reflection to dynamically invoke methods.

1. Pom.xml

Here we use Spring Boot 1.4.3:

pom.xml
<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 will call the second bean’s method using reflection.
  • The second bean is the bean to be called by the server bean, providing some methods to be invoked.
Server.java
@Component("Server")
public class Server {
@Autowired
private ApplicationContext appContext; // Here we inject the Spring application context for later use.
}
MethodsBean.java
@Component("MethodsBean")
public class MethodsBean {
public void aMethod() {
System.out.println("test");
}
}

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

Now comes the trick:

String methodName = "aMethod"; // The method to be called
Object bean = appContext.getBean("MethodsBean"); // Defined by the @Component parameter
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 parameter to search for the Method object.
  • If the method object is found, use Java reflection to invoke the method.

Summary

In this post, we explored how to use Java reflection to dynamically call methods in a Spring bean. By leveraging the ApplicationContext and reflection APIs, you can invoke methods whose names are not known at compile time. This approach is useful in scenarios where flexibility and dynamic behavior are required. However, always consider the performance and security implications of using reflection.

Final Words + More Resources

My intention with this article was to help others who might be considering solving such a problem. So I hope that’s been the case here. If you still have any questions, don’t hesitate to ask me by email: Email me

Here are also the most important links from this article along with some further resources that will help you in this scope:

Oh, and if you found these resources useful, don’t forget to support me by starring the repo on GitHub!