工作遇到一个问题,返回对象的参数需要固定定义在一个类中
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对占位符进行替换。做好这个方法很简单,但是没有用过就很难想到。