最近在重构,有一个地方,需要判断当前请求体所有字段为 null 则不向服务层发起请求, 由于对 java 不是很熟悉,网上说通过 java 反射可以实现,在学习了反射后,给出以下两个例子
以下给出 js 及 java 的例子
js 实现
function checkObjectAllNull(obj) {
if (!(obj instanceof Object)) {
throw Error("不合法类型") ;
}
const values = Object.values(obj);
if (values.length == 0) { return true; }
return values.every((it) => { return it == undefined; });
}
运行结果
image.png
java 实现
UserTest.java
public class UserTest {
Integer age;
String name;
public UserTest(Integer age, String name) {
this.age = age;
this.name = name;
}
}
通过反射获取
private Boolean checkObjectAllNull(Object object) throws IllegalAccessException {
Class<?> clz = object.getClass();
Field[] declaredFields = clz.getDeclaredFields();
Boolean flag = true;
for (Field field : declaredFields) {
field.setAccessible(true);
if (field.get(object) != null) {
return false;
}
}
return true;
}
@Test
public void testNull() throws IllegalAccessException {
UserTest userTest = new UserTest(null, null);
UserTest userTest2 = new UserTest(1, "");
UserTest userTest3 = new UserTest(1, null);
System.out.println(checkObjectAllNull(userTest));
System.out.println(checkObjectAllNull(userTest2));
System.out.println(checkObjectAllNull(userTest3));
}
执行 testNull 运行结果:
true
false
false
参考学习:
https://www.cnblogs.com/chanshuyi/p/head_first_of_reflection.html
网友评论