BeanUtils.copyProperties(Object source, Object target)
将source和target实体类中共有的字段进行复制,spring-beans包下的工具类,底层原理也比较简单 反射判断属性名, 也有可能会遇到坑,例如get set方法名不正确 BeanUtils.copyProperties为null的问题new DefaultMapperFactory.Builder().build().getMapperFacade().map(Object source, Target.class)
与BeanUtils 相比 这个方法可以自定义转换字段名 并且基于javassist技术, beanutils是基于反射的,例如源实体类字段是num 我们需要复制到目标实体的age字段,此外还可以复制 List<?> 方法:
new DefaultMapperFactory.Builder().build().getMapperFacade().mapAsList(Object source, Target.class)
public void mapperFactory() {
DefaultMapperFactory factory = new DefaultMapperFactory.Builder().build();
// Import 实体类里面存在有int num 字段 ; People实体类存在 int age字段
Import it = new Import();
it.setNum(11);
// 需要拷贝不同字段名时的处理
factory.classMap(Import.class,People.class).field("num","age").byDefault().register();
People peopleAfter = factory.getMapperFacade().map(it, People.class);
// 此时 peopleAfter.age == it.num == 11
System.out.println(peopleAfter);
}
需要使用orika-core jar包 , maven依赖如下
<dependency>
<groupId>ma.glasnost.orika</groupId>
<artifactId>orika-core</artifactId>
<version>1.5.4</version>
</dependency>
Properties prop = PropertiesLoaderUtils.loadAllProperties("yourDirName/xx.properties");
动态加载配置文件,即配置文件加载,可以实时读取到,原理是因为每次classLoader会去重新加载 , 参数为配置文件的相对路径, spring-core包下的工具类ResourceBundle bundle = ResourceBundle.getBundle("xx"); String name = bundle.getString("name");
简洁的代码加载资源路径根目录下的xx.properties配置文件(非动态),例如xx配置中存在某个key为 “name”,想要获取value, 可以使用上述方法,java.util下的类- ::参数转成String ,双冒号参数优点不言而喻。
/**
* Description: 函数式参数转回String属性名
* date: 2021/06/09 12:05
*
* @param sFunctionField
* @return
* @author qkj
*/
public static <T> String function2Str(SFunction<T, ?> sFunctionField) {
Method writeReplace = null;
try {
// 函数式方法可以直接调用writeReplace
writeReplace = sFunctionField.getClass().getDeclaredMethod("writeReplace");
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
writeReplace.setAccessible(true);
String fieldName = "";
try {
// 序列化
Object object = writeReplace.invoke(sFunctionField);
// 反序列化
SerializedLambda serializedLambda = (SerializedLambda) object;
String methodName = serializedLambda.getImplMethodName();
String temp = methodName.substring(3);
fieldName = temp.replaceFirst(temp.substring(0, 1), temp.substring(0, 1).toLowerCase());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return fieldName;
}
- Optional 类非空处理 jdk8新特性 支持对null时的处理
People people = null;
String s = Optional.ofNullable(people)
.map(item -> item.getName())
.orElse("---");
// 得到 “---” 字符串
System.out.println(s);
List<People> list = null;
// 得到一个空list对象 而非null值
List<People> list1 = Optional.ofNullable(list).orElse(new ArrayList<>());