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

如何在嵌套Map结构的Properties对象中使用getProperty()取值

解决嵌套Map结构下Properties获取内层值的问题

嘿,我来帮你搞定这个问题!首先得搞清楚Properties的本质——它是Hashtable<Object, Object>的子类,而getProperty()方法是专门为扁平的String键值对设计的。你现在把嵌套的Map<String, Map<String,String>>塞进去了,内层的mp1是个Map对象,不是String,所以直接用getProperty("from")肯定拿不到想要的结果。

要拿到内层的from值,得分两步走:

第一步:取出外层对应的内层Map

因为你用properties.putAll(mp2)把mp2的键值对存进了Properties,所以得先用get()方法(注意不是getProperty())把testing对应的内层Map取出来,还要做个强制类型转换:

Map<String, String> innerMap = (Map<String, String>) properties.get("testing");

这里用get()是因为它返回的是原始的Object类型,能拿到实际的Map对象,而getProperty()会把值转成String,拿到的只是Map的字符串表示,没法直接从中提取有效数据。

第二步:从内层Map里拿目标值

拿到innerMap之后,就和操作普通HashMap一样,直接用get()方法取from的值就行:

String fromValue = innerMap.get("from");
System.out.println(fromValue); // 输出 somethingfrom

完整可运行代码

把这段逻辑加到你的代码里,我还加了类型检查和安全转换的处理,避免潜在的类型转换异常:

import java.util.*;
public class setPropertyTest {
    public static void main(String[] args) {
        Map<String, String> mp1 = new HashMap<>();
        mp1.put("from", "somethingfrom");
        mp1.put("to", "somethingTO");
        Map<String, Map<String,String>> mp2 = new HashMap<>();
        mp2.put("testing", mp1);
        Properties properties = new Properties();
        properties.putAll(mp2);

        // 安全获取内层from值的代码
        Object testingValue = properties.get("testing");
        if (testingValue instanceof Map<?, ?>) {
            @SuppressWarnings("unchecked")
            Map<String, String> innerMap = (Map<String, String>) testingValue;
            String fromValue = innerMap.get("from");
            System.out.println("from对应的值是:" + fromValue);
        }
    }
}

额外提醒

其实Properties的设计初衷是存储配置文件那种扁平的String键值对(比如key=value形式)。如果你的数据是嵌套Map结构,用普通的Map来存储会更贴合场景,没必要硬套Properties。但如果因为某些限制必须用Properties,那上面的方法就是最直接可靠的解决方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:19:36