關鍵詞:java註解、反射
直接貼代碼:
註解類如下:
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD})//次註解作用於類和字段上
public @interface MyNotNull {
}
工具類如下:
public class StringUtil {
/**
* 根據對象上的註解來判斷屬性是不是爲空
*
* @author
* @date 2019/2/15 17:27
*/
public static boolean isEmptyAnnotation(Object object) throws Exception {
if (object != null) {
// 拿到該類
Class<?> clz = object.getClass();
// 獲取實體類的所有屬性,返回Field數組
Field[] fields = clz.getDeclaredFields();
for (Field field : fields) {
/*獲取私有的*/
field.setAccessible(true);
/*判斷是不是使用MyNotNull註解*/
if (field.getDeclaredAnnotation(MyNotNull.class) == null) {
break;
}
/*如果爲空返回true*/
/*StringUtils工具類爲org.apache.commons.lang所屬*/
if (field.get(object) == null || StringUtils.isEmpty(field.get(object).toString())) {
return true;
}
}
}
return false;
}
/**
* 判斷是否爲空
* null或空字符串
* 是:true
* 否:false
*
* @author
* @date 2019/2/15
*/
public static boolean isEmpty(String... strArray) {
for (String str : strArray) {
if (StringUtils.isEmpty(str)) {
return true;
}
}
return false;
}
}