One 、 Preface
Today, I will share a common tool class with my friends , There are four methods in total , It is widely used , It is used to verify that an object or the specified attribute in the object is null , Return the exception directly , Check the front-end request parameters ; When the value is not empty , Perform the specified action , Can reduce a lot of if Conditions , Such as :mybatis Request parameter settings ; It is also used to judge when the value is not empty , Replace with a new value , Complete the following actions .
This description may not be clear enough , Here I list several usage scenarios , More scenarios require small partners to make rational use of... According to their business needs .
// Scene one , When you click login , Back end verification user name
if(StringUtils.isEmpty(name)){
throw new Exception(" Login user name cannot be empty ");
}
// Scene two : Convert property contents to new values
String address = " Hangzhou, Zhejiang Province ";
if(StringUtils.isNotEmpty(address)){
address =" Address :"+address;
}
// Scene three : Replace too many if Conditions
SysUserDto userDto = new SysUserDto();// Front end parameters
SysUser user = new SysUser();//mybatis Parameters
if(StringUtils.isEmpty(userDto.getName())){
user.setUserName(userDto.getName())
}
if(StringUtils.isEmpty(userDto.getPwd())){
user.setPassword(userDto.getPwd())
}
Copy code
\
Two 、 Text
First create a test entity class :
import lombok.Data;
@Data
public class SysUser{
private String name;
private String password;
}
Copy code
2.1 Check that multiple objects cannot be empty
- Test example
SysUser user = new SysUser();
SysUser user2 = null;
Args.notEmptys(user,user2);
Copy code
- Method content
public static void notEmptys(Object... objects) {
for (Object obj : objects) {
if (obj == null) {
throw new BusinessException(" Property cannot be empty ");
}
if (obj.toString().trim().isEmpty()) {
throw new BusinessException(" Property cannot be empty ");
}
}
}
Copy code
- test result
Exception in thread "main" Property cannot be empty
at com.basic.business.utils.Args.notEmptys(Args.java:27)
at com.basic.business.demo.DemoController.main(DemoController.java:43)
Copy code
2.2 The verification object property cannot be empty
If the parameter 【Boolean isAll】 Set to true, All properties will be verified ; If set to false, You need to put the detection field into 【propertys】 in .
- Test example
SysUser user = new SysUser();
// Use a : Verify all parameters
Args.checkField(user,true,"");
// Use two : Check only password Parameters
Args.checkField(user,false,"password");
Copy code
- Method content
/** * Object multi field null check * @param obj The object being examined * @param isAll Check all parameters * @param propertys Fields in the checked object Can be more */
public static void checkField(Object obj, Boolean isAll, String... propertys) {
if (obj != null) {
Class<? extends Object> clazz = obj.getClass();
if (isAll) {
PropertyDescriptor[] propertyDescriptors = BeanUtils.getPropertyDescriptors(clazz);
for (int p = 0; p < propertyDescriptors.length; p++) {
checkEachField(obj, propertyDescriptors[p]);
}
} else {
if (propertys != null && propertys.length > 0) {
// Traverse all properties
for (int i = 0; i < propertys.length; i++) {
String property = propertys[i];
// Get attribute information
BeanUtils.getPropertyDescriptors(clazz);
PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(clazz, property);
checkEachField(obj, pd);
}
}
}
}
}
private static void checkEachField(Object obj, PropertyDescriptor pd) {
Class<? extends Object> clazz = obj.getClass();
String property = pd.getName();
if (pd != null) {
// Gets the name of the current field javabean Reading method
Method readMethod = pd.getReadMethod();
if (readMethod != null) {
Object invoke = null;
try {
invoke = readMethod.invoke(obj);
} catch (Exception e) {
throw new BusinessException(" Method " + readMethod.getName() + " Unable to execute ");
}
if (invoke != null) {
//String Types are handled separately
Class<?> propertyType = pd.getPropertyType();
if ("java.lang.String".equals(propertyType.getName())) {
if (StringUtils.isBlank((String) invoke)) {
throw new BusinessException(" error : [ " + property + " ] Can't be empty !");
}
} else if ("java.util.List".equals(propertyType.getName())) {
List list = (List) invoke;
if (list.size() == 0) {
throw new BusinessException(" error : [ " + property + " ] Can't be empty !");
}
}
} else {
throw new BusinessException(" error : [ " + property + " ] Can't be empty !");
}
} else {
throw new BusinessException(" stay " + clazz + " in Can't find " + "[ " + property + " ] Of Reading method ");
}
} else {
throw new BusinessException(" stay " + clazz + " in Can't find " + "[ " + property + " ] attribute ");
}
}
Copy code
- test result
Usage one result :
Exception in thread "main" error : [ name ] Can't be empty !
at com.basic.business.utils.Args.checkEachField(Args.java:116)
at com.basic.business.utils.Args.checkField(Args.java:77)
Usage 2 Results :
Exception in thread "main" error : [ password ] Can't be empty !
at com.basic.business.utils.Args.checkEachField(Args.java:116)
at com.basic.business.utils.Args.checkField(Args.java:77)
Copy code
2.3 Execute the specified action when the parameter is not empty
We often encounter such scenes , Assemble database query conditions according to front-end parameters , If it is not empty, we will set the front-end value to be the entity class , Or as in the following example , When name Isn't empty , Add to list among .
- Test example
List list = Lists.newArrayList();
SysUser user = new SysUser();
user.setName("huage");
Args.doIfNotEmpty(user.getName(),list::add);
System.out.println(list);
Copy code
- Method content
public static <R, T> R doIfNotNull(T t, Callback<T, R> callback) {
try {
return t == null ? null : callback.call(t);
} catch (Exception e) {
throw new BusinessException("[doIfNotNull error]", e);
}
}
Copy code
- test result
[huage]
Copy code
2.4 Use the new value when the parameter is empty , And complete the specified action
This method and 2. More similar , Only when the target value is not empty , Use the new value for subsequent operations , As in the following example ,name The initial value is 【test】, After execution doIfNotNullNewValue The new value will be 【huage】 Add to list in ,.
- Test example
List list = Lists.newArrayList();
SysUser user = new SysUser();
user.setName("test");
Args.doIfNotNullNewValue(user.getName(),"huage",list::add);
System.out.println(list);
Copy code
- Method content
public static <R, T> R doIfNotNullNewValue(T t,T newt, Callback<T, R> callback) {
try {
return t == null ? null : callback.call(newt);
} catch (Exception e) {
throw new BusinessException("[doIfNotNull error]", e);
}
}
Copy code
- test result
[huage]
Last
If you think this article is of little help to you , Point a praise . Or you can join my development communication group :1025263163 Learn from each other , We will have professional technical questions and answers
If you think this article is useful to you , Please give our open source project a little bit star:https://gitee.com/ZhongBangKeJi/crmeb_java Thank you for !