Dynamic Sorting With Java @ JDJ

来源:互联网 发布:python入门书籍 知乎 编辑:程序博客网 时间:2024/05/01 21:23
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>

  Those familiar With the Java.util.Comparator interface of the Java API realize its capabilities for Sorting a collection of objects based on an attribute of the objects in the collection. This works well when there is only a single field in which Sorting is required. When more complex Sorting is necessary, the limitations of Sorting on a single field become obvious. What about the situation in which a user desires the functionality to sort selectively on any field in object collection? This article describes an implementation of the Comparator interface that along With the reflection API allows an object to be sorted Dynamically on any of its publicly accessible fields.

  Problem Statement

  Let's describe the problem a bit more specifically. A collection of employee Transfer Objects (EmployeeTO class) exists. (For a description of the Transfer Object design pattern consult a software design pattern book.) Each EmployeeTO in the collection is a data container object for a single employee's information. For this example, our simplified EmployeeTO object contains only three pieces of data - employee ID, last name, and salary.

  JDJ=on&issue=506" />

  A Human Resources application also exists that uses this collection to display a list of all employee data to HR application users. The users of this system have the following requirements:

  Allow Sorting on any field on the report

  Allow control of the sort order Simple Solution

  Before delving into our Dynamic Sorting solution that allows Sorting on any attribute, let's first look at a simple solution that supports Sorting on a single attribute only. This will demonstrate the basic behaviors of Comparator and from this we'll be able to glean the improvements we wish to make. This solution utilizes the more common use of the Comparator interface. There are two classes required to implement this.

  EmployeeTO - Simple Version

  First, our EmployeeTO can be made sortable by implementing the Comparator interface as shown in Listing 1. In addition to the getters and setters for ID, last name, and salary, EmployeeTO must implement the compare() and equals() methods in order to meet the Comparator's requirements. These methods define how EmployeeTO is to be sorted. The compare() method takes two parameters, both of type Object. Note that compare() returns an int. This return value tells the sort engine the collating sequence equality of two attribute values from each of the object parameters passed to compare(), respectively. We need to write the code that performs this evaluation. The first step in compare() is to cast the two parameters' objects to EmployeeTO objects and extract the employee IDs by calling the getId() method on each object in turn. Now we can compare the values. There are really only three possible outcomes that can result from this comparison. Table 1 describes the results based on these outcomes.

  The other method we must code is the equals() method. Although this method is not used for Sorting, it must be implemented in order to meet the contract of the Comparator interface.

  Sorting the Collection - Simple Version

  The SimpleTest class in Listing 2 adds three EmployeeTO objects to a List, then performs a sort on that Collection. (Listings 2-5 can be downloaded from www.sys-con.com/Java/sourcec.cfm.) Line 30 of SimpleTest calls the static sort() method of the Collections class to actually perform the sort as follows.

  Collections.sort(elements, new EmployeeTO());

  The first parameter passed to sort() is the collection object we wish to have sorted. The second parameter is an object of type Comparator that contains the customized Sorting logic - in this case EmployeeTO, which implements the Comparator interface. We certainly could have passed any instance of EmployeeTO as the second parameter to the above method call. However, instead of reusing one of the three values initially added to the collection, I chose to pass a new instance of the class for purposes of clarity.

  A quick note on encapsulation and responsibility assigning seems to be in order here. In this case, it makes sense to encapsulate the specific compare() method Sorting logic Within EmployeeTO. With the information we have thus far, EmployeeTO is the only class that requires the knowledge of how it should be sorted. Later, as a Dynamic Sorting solution is provided, we'll see this Sorting logic moved out of the Transfer Object class as the Sorting logic becomes less specific to any one particular Transfer Object implementation.

  This implementation will run but falls short when it comes to meeting the user's requirements. Remember, we need to be able to sort on any one of the three fields in EmployeeTO based on a user's choice. And let's not forget about the ability to control the sort order.

  Enhancement Options

  Let's think about the options that are available to improve what we have and meet the requirements. One option is to code nested if/else statements in our compare() method to allow for Sorting on any field in the object based on some field name parameter passed to EmployeeTO. The problem With this solution is that it's difficult to maintain and the code could get rather lengthy as well. If new fields are added to EmployeeTO, we must update compare() appropriately.

  What we would really like to do is invoke any given getter method of our Transfer Object at runtime Without having to specifically hard code each possible method call in the compare() method. If we could do this, we could use the results of those method calls to Dynamically determine equality. In addition, it would be desirable if this Dynamic Sorting could be reused for any Transfer Object. The good news is that this functionality can be achieved by leveraging the reflection API and the flexibility of the Collections.sort() method.

  Reflection

  The Java.lang.reflect.Method class provides the ability to invoke a method of a given object based on the value of a string. For example, using a string containing the value "getId", the method getId() of EmployeeTO can be Dynamically invoked at runtime. This string value can then be changed as we wish to cause any of the methods of EmployeeTO to be called.

  The reflection API provides a variety of interesting features including the ability to pass parameters to methods and the ability to determine method return types. (For a complete list of these capabilities, consult the Java API Javadoc.) We will need the latter capability as the three getter methods of EmployeeTO return different types and it will thus be necessary to be aware of which type we have when doing the comparison in the compare() method. For example, we'll need to code a different sort of equality test on an int return value as opposed to a string.

  Java.util.Collections.sort()

  A Dynamic solution will also need to take advantage of the flexibility of the Collections.sort() method. Recall that in our simple Sorting solution we passed an instance of an object that implemented the Comparator interface as the second parameter to Collections.sort(). In that case, it was the EmployeeTO object that contained the Sorting logic. This worked great for what we needed it to do. Now, however, we want something a bit more sophisticated and flexible. What if we were to create a class that implemented Comparator, which was separate from each Transfer Object? In it we could place our Dynamic Sorting code and simply pass an instance of this new class as the second parameter to Collections.sort().

  Doing this would cause several desirable results. First, we'll have completely decoupled any Sorting logic from our Transfer Objects. This is highly desirable as it decreases not only the size of each Transfer Object by essentially eliminating the need for Sorting code, but also removes the need for coding individual field comparison logic. Second, we'll have created a reusable utility class that can be used in many different situations where Sorting is required. While reusability is not a specifically stated user requirement for our design, it is certainly desirable.

  Dynamic Solution

  Figure 1 is a UML diagram (With attribute and method details omitted) that shows how the components of both the simple and the Dynamic Sorting solutions fit together. Really, the only portion that has changed since our simple solution is where the Comparator interface gets implemented. In the first example, EmployeeTO implemented Comparator directly. Now DynamicComparator implements Comparator and contains an intelligent implementation of the compare() method that can be used by any class that requires a collection of objects to be sorted.

  DynamicComparator

  Listing 3 shows the completed code listing for DynamicComparator. There are a number of interesting things about this class. First, note the class signature. The class implements two interfaces - Comparator and Serializable. Comparator should come as no surprise since that interface is the essence of the Sorting capabilities we desire. Also, although not a requirement, the API docs recommend that any class implementing Comparator implement Serializable as well.

  Second, look at the static sort() method. Classes wishing to utilize DynamicComparator will call this method rather than Collections.sort(). I've decided to make sort() static to mimic the Collections.sort() method. Although the DynamicComparator.sort() method is called statically, internally DynamicComparator creates an instance of itself. This is necessary in order for it to provide access to the nonstatic compare() and equals() methods of the Comparator interface that it supports. Next note how this method takes three parameters. The first is the collection object to be sorted. The second is a string that defines the field of each object in the collection on which Sorting should be performed. The last parameter is a Boolean specifying the sort order. These three parameters are used as arguments to create a new instance of DynamicComparator that is the second parameter passed to the Collections.sort() method.

  Third, take a look at the compare() method. This is where the reflection code really kicks in. One of the first things we need to obtain is a reference to a method object at line 43. We'll use this reference to call methods Dynamically. This task is done using the getMethod() helper method, which obtains this value via reflection. Next, we need to determine the return type of the methods we are about to call. Remember that we will need to compare the attribute values of the two objects passed into compare(). If the return type is an int, for instance, we'll certainly have to write different code to do the comparison than if the return type is a string. Once we have the return type, we examine it and, based on its value, Dynamically perform the actual method invocation and resulting comparison of the two values.

  Note that currently there are three separate "if" test blocks - one each for string, int, and double. The implementation requires comparison logic for any method return type we expect to encounter. For the range of return types in our EmployeeTO example, these three are sufficient. However, additional code would need to be added to DynamicComparator if comparisons of other types are required - short, Java.util.Date, Java.math.BigDecimal, etc. Coding for each specific return type here is unavoidable as there is no way to Dynamically cast Java objects. Similarly, Java-supplied nonobject data types like int, long, and double use entirely different comparison operators than do first-class object types like String or Date.

  There are some other important points about this code. First, DynamicComparator fully supports null values. If either or both of the arguments passed to compare() are null, this method knows how to handle the situation accordingly. Second, look at each return statement Within compare(). Remember the requirement that the user be able to control not only the sort field but also the sort order? This code supports the latter by essentially reversing the default sort order With a call to getSortOrder(). This is done if the user has decided to sort the result in descending order based on the Boolean value passed into the constructor from the sort() method. Third, the constructMethodName() method converts a Transfer Object attribute name string into a method name by prepending a "get" string and capitalizing the first character of the passed value. For instance, constructMethodName() would convert "salary" to "getSalary".

  Last, the equals() method is needed to complete the interface requirements.

  EmployeeTO - Enhanced Version

  Listing 4 shows the enhanced version of EmployeeTO. The most obvious change is that EmployeeTO is now even simpler than before. Now that all of the Sorting logic has been moved to DynamicComparator and the class no longer implements Comparator, we don't need to implement the compare() and equals() methods.

  Sorting the Collection - Dynamic Version

  Listing 5 is the code for DynamicTest. The only change between this class and SimpleTest is how the sort is called. Here we pass the three parameters to DynamicComparator.sort() (Collection Object, the decapitalized attribute name, and sort ascending flag) and let the DynamicComparator do the rest.

  DynamicTest could just as easily have sorted on last name by passing "lastName" or on employee ID by passing "id" as the second parameter on line 29.

  Solution Discussion

  Building a class such as DynamicComparator has many benefits in an application that requires robust Sorting capabilities. In this design, we have created a reusable, loosely coupled API that can be used to sort a collection of objects based on getter methods. The sort field is easily configurable and also allows control over the sort order.

  This design, however, is not Without trade-offs. Although using the reflection API allows us to do lots of cool things, using reflection can slow performance. This is particularly true in applications using pre-1.4 versions of Java. In addition, it's possible that applications wishing to sort very large collections may find DynamicComparator too slow.

  Other inadequacies of DynamicComparator might become evident as well. Although it allows Sorting on any one attribute of a collection of objects in an easily configurable manner, DynamicComparator does not address the potential need to sort by multiple fields - primary and secondary field sorts like that occur automatically With the ORDER BY clause in Structured Query Language (SQL).

  Conclusion

  This article introduced a reusable implementation of the Comparator interface that utilizes Java reflection to Dynamically sort a collection of objects on any one of any number of fields Within that object.

  If your application or framework has a need for this specific functionality, perhaps this design will fit your needs.

<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>