Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8894209
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T23:26:17+00:00 2026-06-14T23:26:17+00:00

I have a List of Value Objects [VO]. These Objects have many properties and

  • 0

I have a List of Value Objects [VO]. These Objects have many properties and corresponding get/set methods. I want to sort this 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 sortType in runtime, which can be either "id" or "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. May be I didn’t use it properly. I don’t want to use conditional if block branching to create whichever new specific Comparator [anonymous inner Class] is needed (at the runtime). Any other thoughts?


The try catch should be inside the new class. Here is the working code. If you want to use a separate class for Comparator, please find it in @Bohemian’s comment below.

        String sortType = "name"; // determined at runtime
        Collections.sort(results, new Comparator<Employee>() {
        public int compare(Employee c1, Employee c2) {
            try{
            Method m = c1.getClass().getMethod("get" + StringUtils.capitalize(sortType));
            String s1 = (String)m.invoke(c1);
            String s2 = (String)m.invoke(c2);
            return s1.compareTo(s2);
            }
            catch (Exception e) {
                return 0;
            }
        }
       });
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T23:26:18+00:00Added an answer on June 14, 2026 at 11:26 pm

    Create a Comparator for the job:

    public class EmployeeComparator implements Comparator<Employee> {
    
        private final String type;
    
        public EmployeeComparator (String type) {
            this.type = type;
        }
    
        public int compare(Employee e1, Employee e2) {
            if (type.equals("name")) {
                 return e1.getName().compareTo(e2.getName());
            }
            return e1.getId().compareTo(e2.getId());
        }
    
    }
    

    Then to use it

    String type = "name"; // determined at runtime
    Collections.sort(list, new EmployeeComparator(type));
    

    The reflective version would be similar, except you would look for a method on the object of “get” + type (capitalised) and invoke that and hard cast it to Comparable and use compareTo (I’ll try to show the code, but I’m using my iPhone and its a bit of a stretch, but here goes)

    public class DynamicComparator implements Comparator<Object> {
        private final String type;
        // pass in type capitalised, eg "Name" 
        // ie the getter method name minus the "get"
        public DynamicComparator (String type) {
            this.type = type;
        }
        public int compare(Object o1, Object o2) {
            // try-catch omitted 
            Method m = o1.getClass().getMethod("get" + type);
            String s1 = (String)m.invoke(o1);
            String s2 = (String)m.invoke(o2);
            return s1.compareTo(s2);
        }
    }
    

    OK… Here’s how to do it without creating a class, using an anonymous class (with exception handling so code compiles):

    List<?> list;
    final String attribute = "Name"; // for example. Also, this is case-sensitive
    Collections.sort(list, new Comparator<Object>() {
        public int compare(Object o1, Object o2) {
            try {
                Method m = o1.getClass().getMethod("get" + attribute);
                // Assume String type. If different, you must handle each type
                String s1 = (String) m.invoke(o1);
                String s2 = (String) m.invoke(o2);
                return s1.compareTo(s2);
            // simply re-throw checked exceptions wrapped in an unchecked exception
            } catch (SecurityException e) {
                throw new RuntimeException(e); 
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        }
    });
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a list of many Python objects like this: class RangeClass(object): def __init__(self,address,size):
I have List[(String,String)] and I need to sort them by the 2nd value and
I have a list of objects. These objects have three variables, ID, Name, &
I have a List with array of object values. I have to display value
I have a Generic List object which hold below table as its own value.
I have a list. If the value that you've entered is within that list
I have a List where element is: struct element { double priority; int value;
Let's say I have a list of primary keys, for each row one value
I have a singly-linked list containing 1 value in each element. struct listElement {
Lets Say i have a table like this WEB_LIST_TABLE KEY Value ---------------------------------------- 134 google.com

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.