You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Apache Configuration2的YAMLConfiguration读取列表并映射为自定义类集合

解决方案

方案1:手动转换(无额外依赖,推荐)

直接读取配置路径下的原始列表,手动映射到自定义类,可避免依赖冲突问题,代码如下:

import org.apache.commons.configuration2.YAMLConfiguration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

// 假设你已经完成YAMLConfiguration的初始化,实例名为config
List<Map<String, Object>> rawEntries = (List<Map<String, Object>>) config.getList("foo.bar");
List<MyListEntry> entryList = new ArrayList<>();

for (Map<String, Object> rawEntry : rawEntries) {
    MyListEntry entry = new MyListEntry();
    entry.entry1 = (Integer) rawEntry.get("entry1");
    entry.entry2 = (String) rawEntry.get("entry2");
    entryList.add(entry);
}

// JDK 16+ 可简化为stream写法
// List<MyListEntry> entryList = rawEntries.stream().map(rawEntry -> {
//     MyListEntry entry = new MyListEntry();
//     entry.entry1 = (Integer) rawEntry.get("entry1");
//     entry.entry2 = (String) rawEntry.get("entry2");
//     return entry;
// }).toList();

方案2:使用内置Bean填充工具(适合字段多的场景)

如果自定义类字段较多,可使用Apache Commons Configuration自带的BeanHelper自动填充属性,需要先确保引入了commons-beanutils依赖:
Maven依赖配置:

<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.4</version> <!-- 可自行更换为匹配项目的版本 -->
</dependency>

转换代码:

import org.apache.commons.configuration2.HierarchicalConfiguration;
import org.apache.commons.configuration2.beanutils.BeanHelper;
import java.util.ArrayList;
import java.util.List;

// 先获取foo.bar下所有子节点的独立配置实例
List<HierarchicalConfiguration<?>> entryConfigs = config.configurationsAt("foo.bar");
List<MyListEntry> entryList = new ArrayList<>();

for (HierarchicalConfiguration<?> entryConfig : entryConfigs) {
    MyListEntry entry = new MyListEntry();
    // 自动将配置中的属性匹配填充到对象
    BeanHelper.populate(entry, entryConfig);
    entryList.add(entry);
}

注意事项

  • 你的MyListEntry类必须提供无参构造函数,否则反射实例化会失败
  • 如果MyListEntry的字段不是public修饰,需要补充对应属性的getter、setter方法才能被BeanHelper识别

内容的提问来源于stack exchange,提问作者marinier

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 21:57:02