说明
Java中接口接收的表单类、代码中的实体类等,快速验证属性名是否为空,避免业务逻辑出错,为空则抛出异常
仅需一行代码,开箱即用,简便快捷,支持使用Java双冒号操作符或注解指定类字段,可自定义判空逻辑以满足不同需求,Jdk版本1.8/11/17均可使用
使用示例
ValueRuntimeException是我自己的自定义异常
代码demo演示:https://github.com/destinyol/attribute-check
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
|
public static void main(String[] args) { @Data class Test { private String name; private String id; } Test test = new Test(); test.setName("测试1"); test.setId(""); try { AttrCheckUtil.buildWith(test,Test::getId,Test::getName).check(); }catch (ValueRuntimeException e){ System.out.println("拿到报错了,错误码是:"+e.getValue()); } try { AttrCheckUtil.buildWith(test,Test::getId,Test::getName).setException(ValueRuntimeException.class).check(); }catch (ValueRuntimeException e){ System.out.println("拿到报错了,错误码是:"+e.getValue()); }
try { AttrCheckUtil.buildWith(test,Test::getId,Test::getName).setWrongCode(1).check(); }catch (ValueRuntimeException e){ System.out.println("拿到报错了,错误码是:"+e.getValue()); }
try { AttrCheckUtil.buildWith(test,Test::getId,Test::getName).setException(ValueRuntimeException.class).setWrongCode(1).check(); }catch (ValueRuntimeException e){ System.out.println("拿到报错了,错误码是:"+e.getValue()); }
@Data class Test2 { @AttrNotBlank private String name; @AttrNotBlank(wrongCode = 10086) private String id; @AttrNotBlank(wrongCode = 1233211) private String code; } try { Test2 test2 = new Test2(); test2.setName("测试2"); test2.setId("xxxxxx"); AttrCheckUtil.check(test2); }catch (ValueRuntimeException e){ System.out.println("拿到报错了,错误码是:"+e.getValue()); } }
|
源码
主方法类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
| public class AttrCheckUtil {
private static final int baseWrongCode = 1; private static final Class<? extends RuntimeException> baseWrongClass = ValueRuntimeException.class; private static void throwYourOwnException(int wrongCode){ throwYourOwnException(baseWrongClass,wrongCode); } private static void throwYourOwnException(Class<? extends RuntimeException> wrongClass, int wrongCode){ Constructor<? extends RuntimeException> constructor = null; try { constructor = wrongClass.getConstructor(Object.class); RuntimeException runtimeException = constructor.newInstance(wrongCode); throw runtimeException; } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } }
private static boolean isBlank(Object value, Field field) { if (value == null) { return true; } if (value instanceof String) { return ((String) value).isEmpty(); } if (value instanceof Collection) { return ((Collection<?>) value).isEmpty(); } if (value instanceof Optional) { return !((Optional<?>) value).isPresent(); } if (value instanceof URL || value instanceof MultipartFile) { return false; } if (field.getType().isArray()) { return Array.getLength(value) == 0; } if (value instanceof Object[]) { return ((Object[]) value).length == 0; } if (field.getType().isPrimitive() || field.getType().equals(Integer.class) || field.getType().equals(Double.class) || field.getType().equals(Float.class) || field.getType().equals(Long.class) || field.getType().equals(Short.class) || field.getType().equals(Character.class) || field.getType().equals(Byte.class) || field.getType().equals(Boolean.class)) { return false; } return false; }
public static void check(Object object) { if (object == null) { throwYourOwnException(baseWrongCode); } Class<?> clazz = object.getClass(); checkClass(clazz, object); }
@SafeVarargs public static <T> AttrCheckUtil buildWith(T targetObject, FieldGetter<T>... fn) { List<String> fieldNames = new ArrayList<>(); for (FieldGetter<T> tFieldGetter : fn) { String fieldName = convertToFieldName(tFieldGetter); fieldNames.add(fieldName); } return new AttrCheckUtil(targetObject, fieldNames); }
private static void checkClass(Class<?> clazz, Object object) { for (Field field : clazz.getDeclaredFields()) { if (field.isAnnotationPresent(AttrNotBlank.class)) { AttrNotBlank annotation = field.getAnnotation(AttrNotBlank.class); field.setAccessible(true); Object value = null; try { value = field.get(object); } catch (IllegalAccessException e) { throw new RuntimeException(e); }
if (isBlank(value, field)) {
throwYourOwnException(annotation.wrongCode()); } } } if (clazz.getSuperclass() != null) { checkClass(clazz.getSuperclass(), object); } }
private static final Map<Class, SerializedLambda> CLASS_LAMBDA_CACHE = new ConcurrentHashMap<>(); private final Object targetObject; private final List<String> fieldNames; private Class<? extends RuntimeException> exceptionClass = null; private Integer wrongCode = null;
private AttrCheckUtil(Object targetObject, List<String> fieldNames) { this.targetObject = targetObject; this.fieldNames = fieldNames; }
public AttrCheckUtil setException(Class<? extends RuntimeException> exceptionClassIn){ this.exceptionClass = exceptionClassIn; return this; } public AttrCheckUtil setWrongCode(Integer code){ this.wrongCode = code; return this; }
public void check() { for (String fieldName : this.fieldNames) { Field field = null; Class<?> clazz = targetObject.getClass(); while (clazz != null) { try { field = clazz.getDeclaredField(fieldName); break; } catch (NoSuchFieldException e) { clazz = clazz.getSuperclass(); } } field.setAccessible(true); Object value = null; try { value = field.get(targetObject); } catch (IllegalAccessException e) { throw new RuntimeException(e); } if (AttrCheckUtil.isBlank(value, field)) {
if (this.exceptionClass==null){ if (wrongCode == null) throwYourOwnException(baseWrongCode); else throwYourOwnException(this.wrongCode); }else{ if (wrongCode == null) throwYourOwnException(this.exceptionClass, baseWrongCode); else throwYourOwnException(this.exceptionClass, this.wrongCode); }
} } }
private static <T> String convertToFieldName(FieldGetter<T> fn) { SerializedLambda lambda = getSerializedLambda(fn); String methodName = lambda.getImplMethodName(); String prefix = null; if (methodName.startsWith("get")) { prefix = "get"; } else if (methodName.startsWith("is")) { prefix = "is"; } if (prefix == null) { System.out.println("无效的getter方法: " + methodName); } return toLowerCaseFirstOne(methodName.replace(prefix, "")); }
private static String toLowerCaseFirstOne(String s) { if (Character.isLowerCase(s.charAt(0))) { return s; } else { return Character.toLowerCase(s.charAt(0)) + s.substring(1); } }
private static SerializedLambda getSerializedLambda(Serializable fn) { SerializedLambda lambda = CLASS_LAMBDA_CACHE.get(fn.getClass()); if (lambda == null) { try { Method method = fn.getClass().getDeclaredMethod("writeReplace"); method.setAccessible(Boolean.TRUE); lambda = (SerializedLambda) method.invoke(fn); CLASS_LAMBDA_CACHE.put(fn.getClass(), lambda); } catch (Exception e) { e.printStackTrace(); } } return lambda; } }
|
判空注解
1 2 3 4 5
| @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface AttrNotBlank { int wrongCode() default 1; }
|
1 2 3 4
| @FunctionalInterface public interface FieldGetter<T> extends Serializable { Object get(T source); }
|