sort a list of objects based on runtime property

Posted by jijo on Stack Overflow See other posts from Stack Overflow or by jijo
Published on 2012-11-26T15:05:36Z Indexed on 2012/11/27 5:04 UTC
Read the original article Hit count: 143

Filed under:
|
|
|
|

I have an arraylist of VOs. These objects have many properties and corresponding get/set methods. I want to sort this array list based on a property which I'll be getting in runtime. Let me explain in detail. My VO is like this

public class Employee {
    String name;
    String id;

    private String getName() {
        return name;
    }

    private String getId() {
        return id;
    }
}

I will be getting a string ‘sort’ in runtime, which can be either ‘id’ of ‘name’. I want to sort the list based on the value of the string.

I have tried to use comparator and reflection together, but no luck. I don’t want to use an if loop and create new comparator classes. Any other thoughts?

© Stack Overflow or respective owner

Related posts about java

Related posts about list