一般的实现方式:
// 构建签名
TreeMap<String, Object> signParams = new TreeMap<>();
params.put("mobile", "123");
HashMap<String, Object> params = new HashMap<>();
params.put("sign", SignUtil.signByMap(privateKey, signParams));
TreeMap分析:
TreeMap默认排序规则:按照key的字典顺序来排序(升序),和字段放入的前后没有关系
测试:
public static void main(String[] args) {
Map<String,Object> params = new TreeMap<>();
params.put("b1","b1");
params.put("a1","c1");
params.put("c1","c1");
System.out.println(params);
}
{a1=c1, b1=b1, c1=c1}
使用方法,通过反射的方式根据实体类属性值创建TreeMap对象
public static TreeMap<String, Object> parseTreeMap(Object model) throws Exception {
TreeMap<String, Object> param = new TreeMap<String, Object>();
Field[] field = model.getClass().getDeclaredFields();
for (int j = 0; j < field.length; j++) {
String name = field[j].getName();
// 将属性的首字符大写,方便构造get,set方法
name = name.substring(0, 1).toUpperCase() + name.substring(1);
String type = field[j].getGenericType().toString();
if ("class java.lang.String".equals(type)) {
Method m = model.getClass().getMethod("get" + name);
String value = (String) m.invoke(model);
if (!StringUtils.isEmpty(value)) {
param.put(name, value);
}
}
if ("class java.lang.Integer".equals(type)) {
Method m = model.getClass().getMethod("get" + name);
Integer value = (Integer) m.invoke(model);
if (value != null) {
param.put(name, value);
}
}
if ("class java.lang.Short".equals(type)) {
Method m = model.getClass().getMethod("get" + name);
Short value = (Short) m.invoke(model);
if (value != null) {
param.put(name, value);
}
}
if ("class java.lang.Double".equals(type)) {
Method m = model.getClass().getMethod("get" + name);
Double value = (Double) m.invoke(model);
if (value != null) {
param.put(name, value);
}
}
if ("class java.lang.Boolean".equals(type)) {
Method m = model.getClass().getMethod("get" + name);
Boolean value = (Boolean) m.invoke(model);
if (value != null) {
param.put(name, value);
}
}
if ("class java.util.Date".equals(type)) {
Method m = model.getClass().getMethod("get" + name);
Date value = (Date) m.invoke(model);
if (value != null) {
param.put(name, value);
}
}
}
return param;
}
TreeMap<String, Object> signParams = ClassUtil.parseTreeMap(vo)
end