On Java Development

All things related to Java development, from the perspective of a caveman.

Using Java Reflection to call methods of a Java Class

without comments

Introduction

This post shows how to use Java Reflection to call getter methods of a Spring context bean (a POJO). The POJO contains the application’s property values and the values need to be logged to the application’s log-file during the application’s startup phase. Since the property name/value pairs differ across projects this means the bean’s method names for each property are also different since their names reflect the names of the properties. Traditional approaches to logging the property values means writing customized code to explicitly call each method by name. Adding to this, whenever a new property is added, the logic has to be modified to include a call to the new method.

Reflection allows for that code to be written once allowing it to execute across all projects – no matter what the method names for each property happen to be and without further modification. This also means this code can be embedded into baseproject, relieving the developer from having to provide this for every project.

Shown below is the method that has been placed into the ApplicationContextManager of baseproject. The intent is to call this method during the applicaton’s start-up phase, so a call to this method has been placed into StartupServlet of baseproject. The statement is ApplicationContextManager.logApplicationGlobalProperties();

The logic processes all of the methods beginning with “get” so that only the “getter” methods of the ApplicationGlobalProperties class will be called. As stated, this strategy is taken because every project’s “getter” methods will be unique to the project and would mean custom code would have to be written for each project so that the properties can be logged to the log-file. When executed the logic prints the name of the method followed by its value as seen in the list below.

The properties above are of a global nature, meaning that they are usable across all runtime environments i.e “localhost”, “TEST” or “PROD”. Another method has been created for the application properties, appropriately called logApplicationProperties, that reads and logs the values established for those environments. That method is listed below.

 
The example data logged is below.

Written by admin

March 7th, 2014 at 6:03 am

Leave a Reply

You must be logged in to post a comment.