首页 > 解决方案 > Java Spring MVC - 模型中类的动态属性名称

问题描述

存在简单的解决方案如何(C# . NET):

    private void sortData(string param, string type)
    {
        var propertyInfo = typeof(MusicCatalogueRowClass).GetProperty(param);
        if (type == "asc")
        {
            _Data.rows = _Data.rows.OrderBy(o => propertyInfo.GetValue(o, null)).ToList();
        }
        else {
            _Data.rows = _Data.rows.OrderByDescending(o => propertyInfo.GetValue(o, null)).ToList();
        }
        saveDataToFile();
    }

Java Spring(没有.NET)制作?我想按动态名称属性对对象列表进行排序...

非常感谢您的任何建议...

标签: javaspring-mvcdynamicreflectionproperties

解决方案


我的解决方案:

   private void sortData(String param, String type)
{
    try
    {

      List<MusicCatalogueRowClass> newData= _Data.getRows();

      newData.sort(Comparator.comparing(MusicCatalogueRowClass -> {
            try {
                return (Comparable) MusicCatalogueRowClass.getClass().getDeclaredField(param).get(MusicCatalogueRowClass);
            } catch (Exception e) {
                throw new RuntimeException("Ooops", e);
            }
        })); 

      if (type.equals("desc")) {
          Collections.reverse(newData);
      }
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }

    saveDataToFile();
}

推荐阅读