对于没有参数的 getter 方法,试试这个:
Util.isNull(person, "getDetails().iterator().next().getName().getFullName()")
在大多数情况下,它运作良好。基本上,它是尝试使用java反射逐层做空检查,直到到达最后一个getter方法,因为我们对反射做了很多缓存,所以代码在生产中运行良好。请检查下面的代码。
public static boolean isNull(Object obj, String methods) {
if (Util.isNull(obj)) {
return true;
}
if (methods == null || methods.isEmpty()) {
return false;
}
String[] A = methods.split("\\.");
List<String> list = new ArrayList<String>();
for (String str : A) {
list.add(str.substring(0, str.indexOf("(")).trim());
}
return isNullReflect(obj, list);
}
public static boolean isNullReflect(Object obj, List<String> methods) {
if (Util.isNull(obj)) {
return true;
}
if (methods.size() == 0) {
return obj == null;
}
Class<?> className = Util.getClass(obj);
try {
Method method = Util.getMethod(className.getName(), methods.remove(0), null, className);
method.setAccessible(true);
if (method.getName().equals("next")
&& !Util.isNull(Util.getMethod(className.getName(), "hasNext", null, className))) {
if (!((Iterator<?>) (obj)).hasNext()) {
return true;
}
}
try {
return isNullReflect(method.invoke(obj), methods);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
public static Boolean isNull(Object object) {
return null == object;
}
public static Method getMethod(String className, String methodName, Class<?>[] classArray, Class<?> classObj) {
// long a = System.nanoTime();
StringBuilder sb = new StringBuilder();
sb.append(className);
sb.append(methodName);
if (classArray != null) {
for (Class<?> name : classArray) {
sb.append(name.getName());
}
}
String methodKey = sb.toString();
Method result = null;
if (methodMap.containsKey(methodKey)) {
return methodMap.get(methodKey);
} else {
try {
if (classArray != null && classArray.length > 0) {
result = classObj.getMethod(methodName, classArray);
} else {
result = classObj.getMethod(methodName);
}
methodMap.put(methodKey, result);
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// long b = System.nanoTime();
// counter += (b - a);
return result;
}
private static Map<String, Method> methodMap = new ConcurrentHashMap<String, Method>();