简体   繁体   English

使用类的字段自动生成地图

[英]automatically generating a map with the fields of a class

I have the following class 我有以下课程

@Data
public class CMC{

  String f1;
  String f2;
  String f3;      
  public Map<String, Supplier<String>> valuesMap() {
    return ImmutableMap.<String, Supplier<String>>builder()
        .put("f1", this::f1)
        .put("f2", this::f2)
        .put("f3", this::f3)
        .build();
  }

}

As you can see I have a few fields and a map for that contains each field pointing to a function that returns the value of that field. 如您所见,我有一些字段和一个映射,其中包含指向每个函数的映射,该函数返回该字段的值。

The problem with this solution is that a developer may get here and add a new field but forgets to add it to a map. 该解决方案的问题在于,开发人员可能会到达这里并添加新字段,但是忘记将其添加到地图中。

Is there a way to automate this process? 有没有办法使这个过程自动化?

I was hoping for something like lombok to help me with this case. 我一直希望像龙目岛这样的东西可以帮助我解决这个问题。 It's a common thing to need a list of the field from a class and have access to their values. 需要一个类的字段列表并访问它们的值是很常见的。

To solve this I would create an annotation and then somehow use reflection to obtain my desired behavior but I suppose something like this has been already implemented in some tools. 为了解决这个问题,我将创建一个批注,然后以某种方式使用反射来获得所需的行为,但是我想这样的事情已经在某些工具中实现了。

You should look into: Class::getDeclaredFields ; 您应该查看: Class :: getDeclaredFields ; Class::getSuperclass ; 类:: getSuperclass ; and Field . 田野 Together, they should be able to get pretty much what you're looking for... Something like: 在一起,他们应该应该能够得到您想要的东西……

final Map<String, Object> map = new HashMap<>();
Class<?> klass = this.getClass();
while (klass != null) {
    for (final Field field : klass.getDeclaredFields()) {
        if (!field.isAccessible()) {
            field.setAccessible(true);
        }
        map.put(field.getName(), field.get(this));
    }
    klass = klass.getSuperclass();
}

You'll need to handle exceptions, work out where to call this, and confirm if you want to do it for all fields ( private , etc.) or just some, whether to lazily cache the value somewhere, and whether everything needs converting to a String (in which case the Object in the map can be changed). 您将需要处理异常,弄清楚在何处调用此方法,并确认是否要对所有字段( private等)或仅对某些字段执行此操作,是否需要将值延迟存储在某个地方,以及是否需要将所有内容转换为一个String (在这种情况下,可以更改mapObject )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM