【问题标题】:Java Spring MVC - Dynamic property name of class in modelJava Spring MVC - 模型中类的动态属性名称
【发布时间】:2020-08-02 06:12:18
【问题描述】:

如何存在简单的解决方案(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)?我想按动态名称属性对对象列表进行排序...

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

【问题讨论】:

    标签: java spring-mvc dynamic reflection properties


    【解决方案1】:

    我的解决方案:

       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();
    }
    

    【讨论】:

      猜你喜欢
      • 2015-10-26
      • 2017-06-29
      • 2011-05-21
      • 2011-06-19
      • 1970-01-01
      • 2015-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多