import logging
from typing import Type, Any
logger = logging.getLogger(__name__)
class StrUtils:
@staticmethod
def is_empty(string: str) -> bool:
return string is None or string == ""
@staticmethod
def is_not_empty(string: str) -> bool:
return not StrUtils.is_empty(string)
@staticmethod
def is_equals(string1: str, string2: str) -> bool:
if string1 is None or string2 is None:
return False
return string1 == string2
@staticmethod
def equals_ignore_case(str1: str, str2: str) -> bool:
"""
忽略大小写比较两个字符串是否相等
:param str1:
:param str2:
:return:
"""
if str1 is None and str2 is None:
return True
if str1 is None or str2 is None:
return False
return str1.casefold() == str2.casefold()
@staticmethod
def convert_type(value: str, target_type: Type[Any]) -> Any:
"""
类型转换,失败是根据字段类型返回默认值
:param value: 字符串
:param target_type: 目标类型
:return: 转换后的至,失败时返回类型对应的默认值
"""
try:
if target_type == int:
return int(value)
elif target_type == float:
return float(value)
elif target_type == bool:
return value.lower() in ("true", "1", "yes", "on")
else:
return value
except (ValueError, TypeError) as e:
logger.warning(f"Failed to convert {value} to {target_type}: {e}")
if target_type == int:
return 0
elif target_type == float:
return 0.0
elif target_type == bool:
return False
else:
return ""