在做前后端分离的项目时,数据都是通过ajax方式返回给前端的,这个时候如果程序没有做好敏感数据剔除,那么很多数据都会返回给前端。
但是如果每次都返回数据前都写一大串代码去指定返回那些数据,不免显得很麻烦,特别的类中有类的时候。
因此自己实现了一个类抽值工具,可以级联获取值,直接一行代码搞定,反馈给前端。
功能可能还不是很完善,只是实现了基础功能,后续还需要使用慢慢扩展吧,一下是代码,抛砖引玉,各位有好的意见,请指导。
public class BeanCutUtil {
private BeanCutUtil() {
throw new IllegalStateException("Utility class");
}
public static <T> Kv bean(T bean, String... fieldNames) {
Kv kv = Kv.create();
for (String fieldName : fieldNames) {
setValue(bean, kv, fieldName);
}
return kv;
}
public static <T> List<Kv> list(List<T> list, String... fieldNames) {
if (list == null) {
return Collections.emptyList();
}
if (fieldNames == null || fieldNames.length <= 0) {
return Collections.emptyList();
}
List<Kv> kvList = new ArrayList<Kv>();
for (T t : list) {
kvList.add(bean(t, fieldNames));
}
return kvList;
}
private static Kv setValue(Object t, Kv kv, String fieleNames) {
if (kv == null) {
kv = Kv.create();
}
String fieldName = fieleNames;
int pos = fieldName.indexOf('.');
if (pos >= 0) {
fieldName = fieldName.substring(0, pos);
}
Object value = null;
try {
value = ReflectUtil.getValueByFieldName(t, fieldName);
} catch (Exception e) {
}
if (value == null) {
if (ReflectUtil.getFieldByFieldName(t, fieldName) != null) {
kv.set(fieldName, null);
}
return kv;
}
kv.set(fieldName, pos >= 0 ? setValue(value, (Kv) kv.get(fieldName), fieleNames.substring(pos + 1)) : value);
return kv;
}
}演示代码如下:
Device device = new Device();
DeviceModel model = new DeviceModel();
model.setId(1);
model.setName("666MODEL");
model.setSoftware("V1.0.0");
AdminUser user = new AdminUser();
user.setEmail("email");
user.setPassword("123123123");
model.setCreatedBy(user);
device.setModel(model);
device.setDeviceId("564654673412121");
System.out.println(BeanCutUtil.bean(device, "deviceId", "id", "model.name", "model.software", "model.createdBy.password"));打印结果:
{model={software=V1.0.0, createdBy={password=123123123}, name=666MODEL}, id=null, deviceId=564654673412121}