2016-03-02 2 views
0

Я пытаюсь сортировать список объектов по свойству этого объекта. Например, список «люди», объект «человек» и некоторые свойства, такие как «возраст», «длина» и «материнский язык». Я хочу отсортировать этот список по возрасту, длине или материнскому языку. Обычно вы могли бы сделать это как следует:Компаратор bean в Android

public class PersonComparator implements Comparator<Person> { 
    @Override 
    public int compare(Person person1, Person person2) { 
    return person1.getName().compareTo(person2.getName()); 
    } 
} 

Collections.sort(persons, new PersonComparator()); 

Проблема, список свойств достаточно долго, так что делает компаратор для каждого свойства в Java «Android» слишком много работы (это выполнимо, но я ленивый), поэтому я хочу компаратора с отражением. В java это называется компилятором , но я не знаю, как я могу реализовать что-то подобное в java.

ответ

1

BeanComparator Util является частью Apache Commons BeanUtil.

Этого сообщение https://stackoverflow.com/a/23408171/847592 упоминает о доступе к этим библиотекам с помощью импорта android-java-air-bridge.jar

0

Поскольку парень на этом посту сказал, что решение «не было денди» я создал свой собственный класс боба компаратора, который включает в себя сортировку направление. здесь ниже мое решение:

package denavo.ape; 

import java.lang.reflect.Method; 
import java.util.Comparator; 

/** 
* Created by Dennis Van de Vorst on 3-3-2016. 
*/ 

public class _ApeItemComparator implements Comparator<_ApeItem> { 




////////////////////////////////////////////////////////////////////////////////////////////// 
///////////////////////////////////////// Variables ////////////////////////////////////////// 
////////////////////////////////////////////////////////////////////////////////////////////// 

Method method; 
Boolean invertDirection; 




////////////////////////////////////////////////////////////////////////////////////////////// 
///////////////////////////////////////// functions ////////////////////////////////////////// 
////////////////////////////////////////////////////////////////////////////////////////////// 

////////////////////////////////////////////////////////////////////////////////////////////// 
// constructor 

_ApeItemComparator(String methodName, Boolean invertDirection) { 

    // 1. set invertDirection 
    this.invertDirection = invertDirection; 

    // 2. set method 
    try { 
     this.method = _ApeItem.class.getMethod(methodName, null); 
    } catch(Exception e){ 
     e.printStackTrace(); 
     this.method = null; 
    } 

} 



////////////////////////////////////////////////////////////////////////////////////////////// 
// functions : compare 

@Override 
public int compare(_ApeItem apeItem1, _ApeItem apeItem2) { 

    // 1. declare variables 
    String property1 = null, property2 = null; 

    // 2. get the property strings 
    try{ 
     property1 = (String) method.invoke(apeItem1, null); 
     property2 = (String) method.invoke(apeItem2, null); 
    } catch(Exception e){ 
     e.printStackTrace(); 
    } 

    // 3. if the direction is inverted, swap the two strings 
    if (invertDirection){ 
     String temp = property1; 
     property1 = property2; 
     property2 = temp; 
    } 

    // 4. check if the strings are doubles 
    if(property1.matches("([0-9]*)\\.([0-9]*)") && property2.matches("([0-9]*)\\.([0-9]*)")) 
     return compareStringsAsDoubles(property1, property2); 

    // 5. check if they are integers 
    else if(property1.matches("[0-9]+") && property2.matches("[0-9]+")) 
     return Integer.parseInt(property1)-Integer.parseInt(property2); 

    // 6. if they are strings then compare them as strings 
    else 
     return property1.compareTo(property2); 
} 



////////////////////////////////////////////////////////////////////////////////////////////// 
// functions : compare strings as doubles 

private int compareStringsAsDoubles(String double1, String double2){ 
    if (Double.parseDouble(double1) < Double.parseDouble(double2)) 
     return -1; 
    else if (Double.parseDouble(double1) == Double.parseDouble(double2)) 
     return 0; 
    else 
     return 1; 
} 

}

Смежные вопросы