Skip to content
Advertisement

Sorting an array of classes based only on field name

I have an application where a user provides me with the name of a field, e.g name or costInCents, and I have to sort by that field. I have ways of guaranteeing that the field name will be correct. This application causes the complication that I simply cannot make my class Comparable and implement a specific compareTo(), since with a custom implementation of compareTo() I need to know which fields / methods to use at implementation time.

So to achieve this goal, I am trying to use reflection in order to match the field to its accessor. Here’s a MWE of what I want to do.

Class Product is a simple POJO class whose instances I want to pairwise compare:

JavaScript

And my Main class, which is currently incomplete:

JavaScript

Unfortunately, the Arrays.sort() line results in a compile-time error with message Capture of ? instead of Object. I have tried casting the second argument to Comparable<?>, Comparable<? super sorterField.getType(), etc, with no luck. Ideas?

Advertisement

Answer

Possibly the best way – with sorting strategies. No need for reflection, compatible with more complex sorting logic:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement