我在Java中有以下代码,我想最小化它或以更简洁的方式编写它。如果可行,你能帮我吗?
return( Objects.equals(obj1.getMeaning(), obj2.getMeaning())
&& Objects.equals(obj1.getModifies(), obj2.getModifies())
&& Objects.equals(obj1.getOriginalCommentString(), obj2.getOriginalCommentString())
&& Objects.equals(obj1.getReferences(), obj2.getReferences())
&& Objects.equals(obj1.getReturnDescription(), obj2.getReturnDescription())
&& Objects.equals(obj1.getReturnType(), obj2.getReturnType())
&& Objects.equals(obj1.getSuppressions(), obj2.getSuppressions())
&& Objects.equals(obj1.getTemplateTypeNames(), obj2.getTemplateTypeNames())
&& Objects.equals(obj1.getThisType(), obj2.getThisType())
&& Objects.equals(obj1.getThrownTypes(), obj2.getThrownTypes())
&& Objects.equals(obj1.getTypedefType(), obj2.getTypedefType())
&& Objects.equals(obj1.getType(), obj2.getType())
&& Objects.equals(obj1.getVersion(), obj2.getVersion())
&& Objects.equals(obj1.getVisibility(), obj2.getVisibility()))
以字符串形式给出方法列表,然后创建一个 map 函数来逐个测试它们是否是一种好的做法。我读过关于Java反射的文章,但我不是那么精通。
你可以
有一个这样的方法:
<T> boolean equals(T obj1, T obj2, Iterable<? extends Function<? super T, ?>> fns) {
for (Function<? super T, ?> fn : fns) {
if (!Objects.equals(fn.apply(obj1), fn.apply(obj2))) {
return false;
}
}
return true;
}
然后像这样称呼它:
return equals(obj1, obj2, Arrays.asList(Thing::getMeaning, Thing::getModifies));
等。