String.format()
今天在看代码的时候,发现了mybatis的自动生成id的类,里面用到了String.format方法,如下:
public class DateTimeIdGenerator implements IdentifierGenerator { private Random random = new Random(); private SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMddHHmmssSSS"); @Override public Number nextId(Object entity) { synchronized (DateTimeIdGenerator.class) { int rand = random.nextInt(999); String id = String.format("%s%03d", dateFormat.format(new Date()), rand); return Long.parseLong(id); } } }
使用了一个日期加三个随机数字的命名方法来做id,%s就代表替换后面dateFormat.format(new Date()),%03d代表替换后面的三个随机数字rand
拓展一下:
转换符 | 详细说明 | 示例 |
---|---|---|
%s | 字符串类型 | “喜欢请收藏” |
%c | 字符类型 | ‘m’ |
%b | 布尔类型 | true |
%d | 整数类型(十进制) | 88 |
%x | 整数类型(十六进制) | FF |
%o | 整数类型(八进制) | 77 |
%f | 浮点类型 | 8.888 |
%a | 十六进制浮点类型 | FF.35AE |
%e | 指数类型 | 9.38e+5 |
%g | 通用浮点类型(f和e类型中较短的) | 不举例(基本用不到) |
%h | 散列码 | 不举例(基本用不到) |
%% | 百分比类型 | %(%特殊字符%%才能显示%) |
%n | 换行符 | 不举例(基本用不到) |
%tx | 日期与时间类型(x代表不同的日期与时间转换符) | 不举例(基本用不到) |