Files
MiddlePlatform/maibu-netty-server/src/main/java/com/maibu/utils/CompareUtils.java
2026-04-30 15:25:58 +08:00

88 lines
3.8 KiB
Java

package com.maibu.utils;
import com.maibu.core.enums.CompareEnum;
import lombok.extern.slf4j.Slf4j;
/**
* 比较工具类
* 提供基于比较操作符的通用比较功能
*/
@Slf4j
public class CompareUtils {
/**
* 比较两个值是否满足指定的操作符条件
*
* @param operator 比较操作符
* @param targetValue 目标值(用于比较的值)
* @param compareValue 比较值(要比较的值)
* @return 是否满足条件
*/
public static boolean compare(CompareEnum operator, String targetValue, String compareValue) {
if (operator == null || targetValue == null || compareValue == null) {
return false;
}
try {
// 根据操作符执行不同的比较逻辑
switch (operator) {
case EQ:
return compareValue.equals(targetValue);
case NEQ:
return !compareValue.equals(targetValue);
case GT:
return isNumeric(compareValue) && isNumeric(targetValue) &&
Double.parseDouble(compareValue) > Double.parseDouble(targetValue);
case LT:
return isNumeric(compareValue) && isNumeric(targetValue) &&
Double.parseDouble(compareValue) < Double.parseDouble(targetValue);
case GTE:
return isNumeric(compareValue) && isNumeric(targetValue) &&
Double.parseDouble(compareValue) >= Double.parseDouble(targetValue);
case LTE:
return isNumeric(compareValue) && isNumeric(targetValue) &&
Double.parseDouble(compareValue) <= Double.parseDouble(targetValue);
case BETWEEN:
// 范围值用英文中划线分割
String[] rangeValues = targetValue.split("-");
if (rangeValues.length != 2) {
return false;
}
return isNumeric(compareValue) && isNumeric(rangeValues[0]) && isNumeric(rangeValues[1]) &&
Double.parseDouble(compareValue) >= Double.parseDouble(rangeValues[0]) &&
Double.parseDouble(compareValue) <= Double.parseDouble(rangeValues[1]);
case NOT_BETWEEN:
// 范围值用英文中划线分割
String[] notRangeValues = targetValue.split("-");
if (notRangeValues.length != 2) {
return false;
}
return isNumeric(compareValue) && isNumeric(notRangeValues[0]) && isNumeric(notRangeValues[1]) &&
(Double.parseDouble(compareValue) < Double.parseDouble(notRangeValues[0]) ||
Double.parseDouble(compareValue) > Double.parseDouble(notRangeValues[1]));
case CONTAIN:
return compareValue.contains(targetValue);
case NOT_CONTAIN:
return !compareValue.contains(targetValue);
default:
return false;
}
} catch (Exception e) {
log.error("比较操作失败,操作符: {}, 目标值: {}, 比较值: {}", operator.getValue(), targetValue, compareValue, e);
return false;
}
}
/**
* 判断字符串是否为数字
*
* @param str 要判断的字符串
* @return 是否为数字
*/
private static boolean isNumeric(String str) {
if (str == null || str.isEmpty()) {
return false;
}
// 使用正则表达式判断是否为数字
return str.matches("^[+-]?\\d*(\\.\\d+)?$");
}
}