StringUtil.isEmpty理解

本文介绍了编程中如何使用StringUtil.isEmpty方法进行字符串空值检查,包括Java中ApacheCommonsLang库的实现以及Python中的简单替代方案,以提高程序健壮性和可读性,防止空指针异常。
Python3.10

Python3.10

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

StringUtil.isEmpty

在编程中,StringUtil.isEmpty 通常是一个工具类方法,用于检查一个字符串是否为空或者为 null。这个方法在不同的编程语言和库中可能有所不同,但其核心功能是一致的,即提供一种便捷的方式来处理字符串的空值检查。

例如,在 Java 中,Apache Commons Lang 库提供了一个 StringUtils 类,其中包含 isEmpty 方法。这个方法会检查输入的字符串是否为 null、空字符串或者只包含空白字符(如空格、制表符等)。如果输入的字符串满足上述任一条件,isEmpty 方法将返回 true,否则返回 false。

以下是一个简单的使用示例:

import org.apache.commons.lang3.StringUtils;

public class Example {
    public static void main(String[] args) {
        String str = "";
        boolean isEmpty = StringUtils.isEmpty(str); // 返回 true,因为 str 是空字符串
        System.out.println("Is empty: " + isEmpty);
    }
}

更详细些的

String name = "John";

if (StringUtil.isEmpty(name)) {
    System.out.println("姓名为空或者为null");
} else {
    System.out.println("姓名不为空");
}

 如果 name 是空或者null,那么就会输出 "姓名为空或者为null";否则,输出 "姓名不为空"。这种方法可以确保在处理字符串时,避免了空指针异常的发生。

在其他编程语言中,如 Python,可能没有名为 StringUtil 的标准库,但你可以使用简单的条件判断来达到相同的目的:

def is_empty(s):
    return s is None or s == ""

# 使用示例
str = ""
is_empty_str = is_empty(str)  # 返回 True,因为 str 是空字符串
print("Is empty:", is_empty_str)

在实际应用中,isEmpty 方法或类似的函数可以帮助开发者避免因字符串为空而导致的程序错误,例如空指针异常或无效的字符串操作。通过在代码中适当地使用这类方法,可以提高程序的健壮性和可读性。

您可能感兴趣的与本文相关的镜像

Python3.10

Python3.10

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

请为这个类生成基于junit4, mockito的单元测试代码,要求覆盖每个边界条件但是尽量简洁,最好在一个覆盖方法就覆盖各个边界条件。此外OperationResponse返回正确的时候参考这个来写: assertEquals(ResponseCode.OK.getCode(), response.getErrorCode().intValue());。直接给结果,不用打印推导过程。这是代码: @Service public class QueryGroupService { @Autowired private GroupRepository groupRepository; @Autowired private PersonRepository personRepository; @Autowired private PersonProps personProps; @Autowired private PersonGroupMappingService personGroupMappingService; /** * 分页查询group * * @param request 分页查询请求 * @return 查询结果 */ public OperationResponse<BasicPageResponse<GroupDTO>> getGroups(BasicPageRequest<GroupDTO> request) { if (request.getQuery() == null || request.getSort() == null || request.getPage() == null) { return OperationResponse.error(ResponseCode.PARAMETER_INVALID); } GroupDTO groupDTO = request.getQuery(); if (StringUtil.isEmpty(groupDTO.getVmsId())) { return OperationResponse.error(ResponseCode.EMPTY_VMS_ID); } if (!StringUtil.isEmpty(groupDTO.getId())) { return OperationResponse.error(ResponseCode.PARAMETER_INVALID, "group id for pagination query must be null"); } BasicPageResponse<GroupDO> groupDOResponse = groupRepository.getGroupList(request); List<GroupDTO> groupDTOList = DOAndDTOMapperUtils.toGroupDTOList( groupDOResponse.getContent()); BasicPageResponse<GroupDTO> response = new BasicPageResponse<>(); response.setContent(groupDTOList); response.setPage(groupDOResponse.getPage()); return OperationResponse.ok(response); } /** * 通过主键查询单个group的详情 * * @param groupDTO 携带vmsId和主键的查询请求 * @return 查询结果 */ public OperationResponse<GroupDTO> getGroupDetail(GroupDTO groupDTO) { if (StringUtil.isEmpty(groupDTO.getVmsId())) { return OperationResponse.error(ResponseCode.EMPTY_VMS_ID); } if (StringUtil.isEmpty(groupDTO.getId()) || !ObjectId.isValid(groupDTO.getId())) { return OperationResponse.error(ResponseCode.INVALID_GROUP_ID); } String vmsId = groupDTO.getVmsId(); String groupId = groupDTO.getId(); List<GroupDO> groupDOList = groupRepository.getGroupListByIdList(vmsId, Collections.singletonList(groupId)); if (groupDOList == null || groupDOList.isEmpty()) { return OperationResponse.error(ResponseCode.GROUP_NOT_FOUND); } GroupDTO resultGroupDTO = DOAndDTOMapperUtils.toGroupDTO(groupDOList.get(0)); List<String> personList = personGroupMappingService.getPersonMappingWithGroup(vmsId, groupId); if (CollectionUtil.isEmpty(personList)) { return OperationResponse.ok(resultGroupDTO); } OperationResponse<List<PersonDO>> response = personRepository.getPersonNameAndIdListByIdList(vmsId, personList); if (!response.isOk()) { return OperationResponse.error(response); } if (CollectionUtil.isEmpty(response.getResult())) { // TODO 正常情况这里不会为空,是否用其他报错 return OperationResponse.error(ResponseCode.INTERNAL_SERVER_ERROR); } List<PersonDTO> personDTOList = DOAndDTOMapperUtils.toPersonDTOList(response.getResult()); resultGroupDTO.setPersonList(personDTOList); return OperationResponse.ok(resultGroupDTO); } /** * 通过id list获取group详细信息list * * @param groupIdsDTO 携带vmsId及group主键_id list的bean * @return 查询结果 */ public OperationResponse<List<GroupDTO>> getGroupListByIds(GroupIdsDTO groupIdsDTO) { if (StringUtil.isEmpty(groupIdsDTO.getVmsId()) || CollectionUtil.isEmpty(groupIdsDTO.getIds())) { return OperationResponse.error(ResponseCode.PARAMETER_INVALID); } if (groupIdsDTO.getIds().size() > personProps.getQueryGroupBatchSize()) { return OperationResponse.error(ResponseCode.BATCH_SIZE_EXCEED); } if (!groupIdsDTO.getIds().stream().allMatch(ObjectId::isValid)) { return OperationResponse.error(ResponseCode.INVALID_GROUP_ID); } String vmsId = groupIdsDTO.getVmsId(); List<String> groupIds = groupIdsDTO.getIds(); List<GroupDTO> groupDTOList = DOAndDTOMapperUtils.toGroupDTOList( groupRepository.getGroupListByIdList(vmsId, groupIds)); return OperationResponse.ok(groupDTOList); } /** * 通过group id获取组内的person列表 * * @param groupDTO groupDTO * @return 查询结果 */ public OperationResponse<List<PersonDTO>> getPersonListByGroupId(GroupDTO groupDTO) { if (StringUtil.isEmpty(groupDTO.getVmsId()) || StringUtil.isEmpty(groupDTO.getId())) { return OperationResponse.error(ResponseCode.PARAMETER_INVALID); } if (!ObjectId.isValid(groupDTO.getId())) { return OperationResponse.error(ResponseCode.INVALID_GROUP_ID); } String vmsId = groupDTO.getVmsId(); String groupId = groupDTO.getId(); List<String> personIdList = personGroupMappingService.getPersonMappingWithGroup(vmsId, groupId); if (CollectionUtil.isEmpty(personIdList)) { return OperationResponse.ok(Collections.emptyList()); } OperationResponse<List<PersonDO>> response = personRepository.getPersonListByIdList(vmsId, personIdList); if (!response.isOk()) { return OperationResponse.error(response); } if (CollectionUtil.isEmpty(response.getResult())) { // TODO 正常情况这里不会为空,是否用其他报错 return OperationResponse.error(ResponseCode.INTERNAL_SERVER_ERROR); } List<PersonDTO> personDTOList = DOAndDTOMapperUtils.toPersonDTOList(response.getResult()); return OperationResponse.ok(personDTOList); } /** * 返回所有传入的group内部person id的并集 * * @param groupIdsDTO 携带vmsId及group主键_id list的bean * @return 查询结果 */ public OperationResponse<Set<String>> getPersonIdsByGroupIds(GroupIdsDTO groupIdsDTO) { if (StringUtil.isEmpty(groupIdsDTO.getVmsId()) || CollectionUtil.isEmpty(groupIdsDTO.getIds())) { return OperationResponse.error(ResponseCode.PARAMETER_INVALID); } if (groupIdsDTO.getIds().size() > personProps.getQueryGroupBatchSize()) { return OperationResponse.error(ResponseCode.BATCH_SIZE_EXCEED); } if (!groupIdsDTO.getIds().stream().allMatch(ObjectId::isValid)) { return OperationResponse.error(ResponseCode.INVALID_GROUP_ID); } String vmsId = groupIdsDTO.getVmsId(); List<String> groupIds = groupIdsDTO.getIds(); Set<String> personIdSet = personGroupMappingService.getPersonIdsMappingWithGroupIds(vmsId, groupIds).values() .stream().flatMap(List::stream).collect(Collectors.toSet()); return OperationResponse.ok(personIdSet); } }
08-14
package common.servlet; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import security.MenuDisp; import util.StringUtil; import common.CommonMethod; import common.constant.BizExceptionMsg; import common.exception.BizException; @WebServlet("/mainmenu") public class MainMenu extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1. コンテキストパスとパラメータを取得する String ctxPath = request.getContextPath(); HttpSession ses = request.getSession(true); String userId = StringUtil.toString(ses.getAttribute("APP_USER")); // 2. 処理前のログイン時間 Date sysLastLoginDateTime = (Date) ses.getAttribute("sysLastLoginDateTime"); String lastLoginTime = ""; if (sysLastLoginDateTime != null) { lastLoginTime = StringUtil.seirekiToWareki(sysLastLoginDateTime, StringUtil.WarekiFormat.LONG_DATETIME); } // 3. メニュー関連の変数を初期化する String strMenuNm6 = ""; String strMenuNm12 = ""; String strMenuNm14 = ""; String strNone = "none"; String strMenuDisp6 = strNone; String strMenuDisp12 = strNone; String strMenuDisp14 = strNone; String strRootUrl6 = ""; String strRootUrl12 = ""; String strRootUrl14 = ""; // 4. メニューデータを取得する List<Map<String, Object>> resultList = new ArrayList<>(); try { resultList = MenuDisp.getGyoumuAndKanriMenu(userId); } catch (Exception e) { BizException.throwException(BizExceptionMsg.AUTH_ERROR); } String userName = ""; String userShozoku = ""; if (!resultList.isEmpty()) { userName = StringUtil.toString(resultList.get(0).get("氏名")); userShozoku = StringUtil.toString(resultList.get(0).get("所属")); ses.setAttribute("APP_USERNAME", resultList.get(0).get("氏名")); ses.setAttribute("APP_SHOZOKUNAME", resultList.get(0).get("所属")); for (Map<String, Object> map : resultList) { String menuOrder = StringUtil.toString(map.get("メニュー順")); String strMenuNm = StringUtil.toString(map.get("メニュー名称")); String strMenuId = StringUtil.toString(map.get("メニューID")); if ("PS".equals(strMenuId)) { strMenuNm14 = strMenuNm; strMenuDisp14 = ""; strRootUrl14 = strMenuId; } else { switch (menuOrder) { case "6": strMenuNm6 = strMenuNm; strMenuDisp6 = ""; strRootUrl6 = strMenuId; break; case "12": strMenuNm12 = strMenuNm; strMenuDisp12 = ""; strRootUrl12 = strMenuId; break; } } } } // 5. 通知情報を取得する List<Map<String, Object>> infoList = new ArrayList<>();; try { infoList = CommonMethod.getInformation("CM"); } catch (Exception e) { BizException.throwException(BizExceptionMsg.AUTH_ERROR); } // 6. リクエストスコープに保存 request.setAttribute("ctxPath", ctxPath); request.setAttribute("lastLoginTime", lastLoginTime); request.setAttribute("strMenuNm6", strMenuNm6); request.setAttribute("strMenuDisp6", strMenuDisp6); request.setAttribute("strRootUrl6", strRootUrl6); request.setAttribute("strMenuNm12", strMenuNm12); request.setAttribute("strMenuDisp12", strMenuDisp12); request.setAttribute("strRootUrl12", strRootUrl12); request.setAttribute("strMenuNm14", strMenuNm14); request.setAttribute("strMenuDisp14", strMenuDisp14); request.setAttribute("strRootUrl14", strRootUrl14); request.setAttribute("userName", userName); request.setAttribute("userShozoku", userShozoku); request.setAttribute("infoList", infoList); // 7. JSPに転送 request.getRequestDispatcher("/page/menu.jsp").forward(request, response); } }给我将这段代码中的“”字符串变成常量
10-21
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值