Java%s占位符的使用

工作遇到一个问题,返回对象的参数需要固定定义在一个类中

     public static final BizCheckCode regular2 =
            new BizCheckCode("402002","%s:披露日期和预约日期不符,%s",
                              "warn", "regular-2", "定期报告2");
    String code;
    String message;
    String type;
    String columnCode;
    String columnValue;
    private BizCheckCode(String code, String message, String type, String columnCode, String columnValue) {
        this.code = code;
        this.message = message;
        this.type = type;
        this.columnCode = columnCode;
        this.columnValue = columnValue;
    public BizCheckCode copy() {
        return new BizCheckCode(this.code, this.message, this.type, this.columnCode, this.columnValue);
    }
    }

而不能使用类的构造器,这样保证定义的参数的原始值是不会被改变的。对于参数固定的情形是合理的,但是参数需要动态拼接的时候怎么办呢?
其实非常简单,利用类提供的copy方法,获得对象,然后得到具体的属性值进行修改。

        BizCheckCode copy = BizCheckCode.regular2.copy();
        copy.setMessage(String.format(copy.getMessage(), "浦发银行","请进行确认"));

这里没有使用传统的加号拼接String的方法,而是对属性需要替换的地方使用%s进行站位:”%s:披露日期和预约日期不符,%s”,使用String.format对占位符进行替换。做好这个方法很简单,但是没有用过就很难想到。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值