+ Reply to Thread
Results 1 to 2 of 2

Thread: loop reflection problem

  1. #1

    loop reflection problem

    How do I pull the reflection out of this loop and pass in the getter method if that's possible ?
    Code:
    public <E> void sortBy(final String fieldName, final boolean sortAsc, List<E> list){
            Collections.sort(list, new Comparator<E>() {
                    public int compare(E o1, E o2) {
                        return compareFields(o1,o2,fieldName.replace("SortBy", "get"),sortAsc);
                    }
                }
            );
        }
    
        @SuppressWarnings({ "rawtypes", "unchecked" })
        protected <E> int compareFields(E o1, E o2,String fieldName, boolean sortAsc){
            try { 
                Comparable o1Data;
                Comparable o2Data;
                o1Data = (Comparable) o1.getClass().getMethod(fieldName).invoke(o1);
                o2Data = (Comparable) o2.getClass().getMethod(fieldName).invoke(o2);
                if(o1Data == null && o2Data == null){
                    return 0;
                } else if (o1Data == null){
                    return 1;
                } else if (o2Data == null){
                    return -1;
                }
                int result = o2Data.compareTo(o1Data); 
                return (sortAsc) ? -result : result ; 
            }
            catch(Exception e) {
                throw new RuntimeException(e);
            }
        }

  2. #2
    Junior Member
    Join Date
    Jan 2012
    Posts
    30
    If you can assume all the elements are the same type.
    Code:
    public <E> void sortBy(final String fieldName, final boolean sortAsc, List<E> list) throws NoSuchMethodException {
        final Method f = list.get(0).getClass().getMethod(fieldName.replace("SortBy", "get"));
        f.setAccessible(true);
        final int direction = sortAsc ? +1 : -1;
        Collections.sort(list, new Comparator<E>() {
            public int compare(E o1, E o2) {
                return compareFields(o1, o2, f, direction);
            }
        }
        );
    }
    
    @SuppressWarnings({"rawtypes", "unchecked"})
    protected <E> int compareFields(E o1, E o2, Method getter, int sortAsc) {
        try {
            Comparable o1Data = (Comparable) getter.invoke(o1);
            Comparable o2Data = (Comparable) getter.invoke(o2);
            if (o1Data == null)
                return o2Data == null ? 0 : 1;
            if (o2Data == null)
                return -1;
            return sortAsc * o2Data.compareTo(o1Data);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts