开发中,肯定遇到过前人留下的,某个类,需要对另外一个类,一个字段一个字段的 get/set
就像下面的这样
1 2 3 4 5
| b.setF_1(a.getF1() == null ? 1 : a.getF1().shortValue()); b.setF2(a.getF2() == null || "".equals(a.getF2().trim()) ? "f2" : a.getF2().trim()); b.setF_3(a.getF3() == null ? 1 : a.getF3().shortValue()); b.setF4(a.getF4());
|
如果字段名类型都一致,只是个数有差异,直接可以用 BeanUtil.copyProperties,如果只是驼峰转下划线,下划线转驼峰之类的比较有规律的也还好说,配置下转 map 的规则,转了 map 再转回来就可以了。
遇到不仅字段名不一样,没有规则,类型还不一样的,那真是看着前人的代码也难受,自己再往里边儿填的时候也难受。得益于 Java 8 以后的 @nFunctionalInterface,这个功能可以实现的比较 好看 些。
首先要明确一件事情 get 方法其实就一种 Supplier,set 方法是一种 Consumer,那事情就简单了些。
基本思想就是把 get/set 方法当参数传进去,在函数内做转换就可以了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| public static <A, B> void set(Consumer<A> setMethod, Supplier<B> getMethod, A defaultV, Predicate<B> defaultValueCondition, Function<B, A> convertFunction) { B v = getMethod.get();
if (v == null || (defaultValueCondition != null && defaultValueCondition.test(v))) { setMethod.accept(defaultV); } else { if (convertFunction == null) { setMethod.accept((A) v); } else { setMethod.accept(convertFunction.apply(v)); } } }
public static <A, B> void set(Consumer<A> setMethod, Supplier<B> getMethod, A defaultV, Function<B, A> convertFunction);
public static <A, B> void set(Consumer<A> setMethod, Supplier<B> getMethod, A defaultV, Predicate<B> defaultValueCondition);
public static <A, B> void set(Consumer<A> setMethod, Supplier<B> getMethod, A defaultV);
public static <A, B> void set(Consumer<A> setMethod, Supplier<B> getMethod);
|
最终效果
1 2 3 4 5 6 7 8 9 10 11
| b.setF_1(a.getF1() == null ? 1 : a.getF1().shortValue()); b.setF2(a.getF2() == null || "".equals(a.getF2().trim()) ? "f2" : a.getF2().trim()); b.setF_3(a.getF3() == null ? 1 : a.getF3().shortValue()); b.setF4(a.getF4());
GetSet.set(b::setF_1, a::getF1, (short) 1, Integer::shortValue); GetSet.set(b::setF2, a::getF2, "f2", StringUtils::isBlank); GetSet.set(b::setF_3, a::getF3, (short) 1, Integer::shortValue); GetSet.set(b::setF4, a::getF4);
|
对比之下的话,感觉下面的还是比较给力的。
另外还抽出来两个接口,专门用来表示 Get/Set 方法
1 2 3 4 5 6 7 8 9
| @FunctionalInterface public interface IGet<T> { T get(); }
@FunctionalInterface public interface ISet<T> { void set(T t); }
|