Java内省踩坑记录

本文记录了一次在使用Java内省过程中遇到的问题。在将yml内容转换为Pojo时,由于字段命名规则导致报错。通过阅读错误信息和源码,发现内省通过截取get方法名获取参数名,对于参数名全大写的特殊情况(如URL),内省会保持原样。而作者的字段命名第二个字母大写,导致了匹配失败。结论是注意内省时参数名的大小写规范。
摘要由CSDN通过智能技术生成

Java内省踩坑记录

1.背景描述

有个功能需要将yml的内容转成一个POJO。但是在项目启动时出现了报错。

 

问题现场

  • yml文件内容:

xField: "time"
yField: "total_pct"
  • pojo定义:

@Data
public class ChartBean {
    private String xField;
    private String yField;
}
  • 启动方法:

public class ChartYmlConfUtil {
    private final static ThreadLocal<Yaml> YAML = ThreadLocal.withInitial(Yaml::new);
​
    // yml转换为javabean的方法
    public static ChartBean load(String path) {
        final Yaml yaml = ChartYmlConfUtil.YAML.get();
        try (final InputStream inputStream = ChartYmlConfUtil.class.getResourceAsStream(path)) {
            final String conf = CharStreams.toString(new InputStreamReader(inputStream));
            return yaml.loadAs(conf, ChartBean.class);
        } catch (IOException e) {
            throw new RuntimeException(String.format("load yaml from [%s] error", path), e);
        }
    }
​
    // 启动
    public static void main(String[] args) {
        load("/chart.yml");
    }
}
  • 报错信息:

Exception in thread "main" Cannot create property=xField for JavaBean=ChartBean(xField=null, yField=null)
 in 'string', line 1, column 1:
    xField: "time"
    ^
Unable to find property 'xField' on class: com.xyq.test.yml.ChartBean
 in 'string', line 1, column 9:
    xField: "time"
            ^
​
    at org.yaml.snakeyaml.constructor.Constructor$ConstructMapping.constructJavaBean2ndStep(Constructor.java:313)
    at org.yaml.snakeyaml.constructor.Constructor$ConstructMapping.construct(Constructor.java:190)
    at org.yaml.snakeya
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值