RSS

Nested field access with FEST Reflect

18 Jun

Abstract: For one reason or another it’s often needed to access fields which are nested (sometimes deeply nested) within other fields. Of course you can write the logic yourself or (from now on) you can simply use the light-weighted framework FEST Reflect v1.4 (compatible with Java 1.5 and above). This short blog will show you how.

Acknowledgement: My gratitude goes to the open source community and to the following people:
Joel Costigliola for his support and open mind
Jonathan Melly for inspiring the idea of accessing nested fields

Goal: Discover the nested field functionality coming with the new release of FEST Reflect.

The maven dependency for FEST Reflect is as follows:

  <dependency>
    <groupId>org.easytesting</groupId>
    <artifactId>fest-reflect</artifactId>
    <version>1.4</version>
  </dependency>

Example 1: Setting a 1st level nested field

For this example we are going to need a simple service to start with, let’s say BusinessService :

public class BusinessService {
    private final NotificationService notificationService;

    public BusinessService() {
      this.notificationService = new NotificationService();
    }

    public void doBusinessLogic() {
      // ...
      notificationService.notifySomeone();
    }
   
  }

Our BusinessService is doing some business logic and in the end is notifying someone by using the NotificationService:

public class NotificationService {
    private final Logger logger = new Logger();
    private final IClientStatusDao clientStatusDao;

    public NotificationService() {
      this.clientStatusDao = new ClientStatusDao();
    }

    public void notifySomeone() {
      // notification logic goes here
      logger.info("About to update client status");
      clientStatusDao.updateStatus("client notified");
    }
  }

Now, imagine that you have a strong desire to access the logger field member inside the notificationService instance variable of our mighty BusinessService (for example when doing some testing). The path to the logger is: businessService.notificationService.logger

Here is how (line 7) you can take advantage of FEST Reflect:

import static org.fest.reflect.core.Reflection.field;

public class SomeTestClass {
  public void someTestMethod(){
    //some pre-testing logic ...
    Logger loggerMock = Mockito.mock(Logger.class);
    field("notificationService.logger").ofType(Logger.class).in(businessService)//
      .set(loggerMock);
    //some testing logic ...
  }
}

Notice that I’ve specified only “notificationService.logger” as an argument of the org.fest.reflect.core.Reflection.field() method. That’s because we give the root (businessService) of the path as an argument of the in() method. Yes, you’ve guessed it, that’s why I call this example accessing 1st level nested field.

By the way you don’t need to be testing in order to use FEST Reflect there are other situation where you can profit from accessing nested fields.

Example 2: Getting a 2nd level nested generic type field

There is no limit at what level the field at which you are interested is located (as long as you type the correct path to it).
Let’s continue our example and explore the ClientStatusDao class:

public class ClientStatusDao implements IClientStatusDao {
    private final Session session;
    private final List<String> listOfNotifications = Arrays.asList("General Notification", "Greetings");

    public ClientStatusDao() {
      this.session = new SessionImpl();
    }

    public void updateStatus(String newStatus) {
      session.startTransaction();
      // here we can use somehow our list of notifications and update status
      session.stopTransaction();
    }
  }

This time we are going to access an instance variable with a bit more complex type, namely the listOfNotifications which is of a List<String> type. Here is the one and only line you need (assuming you’ve already imported the static field method member (or all static members) of org.fest.reflect.core.Reflection):

List<String> listOfNames = field("notificationService.clientStatusDao.listOfNames").ofType(new TypeRef<List<String>>() {}).in(businessService).get();

Well, that was all for now folks. Please, leave a comment if you would like to share your views,recommendations, use-cases or requests. If you would like to contribute you can do it via GitHub FEST Reflect (you can add your requests at GitHub FEST Project Issues).

P.S.
In case you are wondering what else you can do with FEST Reflect and how to play with field access don’t forget to check my previous post on how to decorate fields (yes, you can decorate nested fields as well).

Advertisements
 
1 Comment

Posted by on June 18, 2012 in Uncategorized

 

One response to “Nested field access with FEST Reflect

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: