Validate.java 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package cn.com.ty.lift.common.verify;
  2. import cn.hutool.core.util.ObjectUtil;
  3. import java.util.Objects;
  4. /**
  5. * <p>
  6. * 条件判断,如果不符合条件,抛出异常
  7. * </p>
  8. * @author wcz
  9. * @since 2020/1/9 8:46
  10. */
  11. public interface Validate {
  12. static ValidateException validateException(String message){
  13. return new ValidateException(message);
  14. }
  15. /**
  16. * 判断表达式是否为真,如果为假,直接抛出异常,返回message
  17. *
  18. * @param expression 需要判断的布尔表达式
  19. * @param message 抛出异常的消息
  20. */
  21. static void isTrue(boolean expression, String message) {
  22. if (!expression) {
  23. throw validateException(message);
  24. }
  25. }
  26. /**
  27. * 判断表达式是否为真,如果为真,直接抛出异常,返回message
  28. *
  29. * @param expression 需要判断的布尔表达式
  30. * @param message 抛出异常的消息
  31. */
  32. static void notTrue(boolean expression, String message) {
  33. if (expression) {
  34. throw validateException(message);
  35. }
  36. }
  37. /**
  38. * 判断对象object是否为空,如果不为空,直接抛出异常,返回message
  39. *
  40. * @param object 参数值
  41. * @param message 抛出异常的消息
  42. */
  43. static void isNull(Object object, String message) {
  44. isTrue(Objects.isNull(object), message);
  45. }
  46. /**
  47. * 判断对象object是否为空,如果为真,直接抛出异常,返回message
  48. *
  49. * @param object 参数值
  50. * @param message 抛出异常的消息
  51. */
  52. static void notNull(Object object, String message) {
  53. isTrue(Objects.nonNull(object), message);
  54. }
  55. static void between(int value, int min, int max, String message){
  56. isTrue(value >= min && value <= max, message);
  57. }
  58. static void notBetween(int value, int min, int max, String message){
  59. isTrue(value < min || value > max, message);
  60. }
  61. static void equals(int one, int other, String message){
  62. isTrue(one == other, message);
  63. }
  64. static void notEquals(int one, int other, String message){
  65. isTrue(one != other, message);
  66. }
  67. static void greater(int value, int bounds, String message){
  68. isTrue(value > bounds, message);
  69. }
  70. static void less(int value, int bounds, String message){
  71. isTrue(value < bounds, message);
  72. }
  73. static void notEmpty(Object object, String message) {
  74. isTrue(ObjectUtil.isNotEmpty(object), message);
  75. }
  76. static void isEmpty(Object object, String message) {
  77. isTrue(ObjectUtil.isEmpty(object), message);
  78. }
  79. static void isBlank(CharSequence cs, String message) {
  80. isTrue(Objects.isNull(cs) || cs.toString().trim().isEmpty(), message);
  81. }
  82. static void notBlank(CharSequence cs, String message) {
  83. isTrue(Objects.nonNull(cs) && cs.toString().trim().length() > 0, message);
  84. }
  85. }