2017-08-15 65 views
0

我有一個列表,其中包含我的POJO類的所有setter。排序列表的方法

public static void main(String[] args) throws Exception { 

    Method[] publicMethods = SampleClass.class.getMethods(); 
    List<Method> setters = new ArrayList<>(); 

    for (Method method : publicMethods){ 
     if (method.getName().startsWith("set") && method.getParameterCount() == 1) { 
      setters.add(method); 
     } 
    } 
} 

在方法列表的文檔順序不能保證。 我的問題是我怎樣才能按照字母順序排列我的列表的列表?

+1

谷歌爲「如何在Java對象進行排序」,點擊數千之一鏈接你得到,並閱讀。 –

回答

2

你需要一個定製comparator

Collections.sort(setters, new Comparator<Method> { 
    @Override 
    public int compare(Method a, Method b) { 
    return a.getName().compareTo(b.getName()); 
    } 
}); 
0

你可以做,使用java8這樣:

List<Method> setters = Arrays.asList(SampleClass.class.getMethods()) 
.stream() 
.filter(
    e->e.getName().startsWith("set") 
).sorted(
    (a, b)-> 
     a.getName() 
     .compareTo(b.getName()) 
).collect(Collectors.toList())