You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从HashMap中获取ID拼接至URL,解决Java空指针异常问题

触发空指针的核心原因

  • 执行顺序错误:拼接URL的代码执行时机早于getid()方法,静态HashMapcreatedValue未初始化、未写入latestDataId键值对,调用get()返回null
  • 元素等待顺序错误:现有代码先获取元素再执行等待,若元素未加载完成会提前抛出异常,终止put操作的执行
  • 边界情况未处理:表格为空时tableValueSize为0,构造的XPath无效,方法异常终止,未完成键值对写入
  • 静态变量线程风险:多用例并发执行时,静态createdValue会被其他用例重置/覆盖,导致取值为空

修复方案

优先建议将getid()改为返回ID字符串的方法,避免静态变量的不可控问题,同时调整等待逻辑、增加非空校验:

优化后的ID获取方法

public static String getid(WebDriver driver) throws InterruptedException {
    String pendingconfirm = buttonXpath_Replace.replace("XXXX", "Pending confirm");
    clickOnButton(driver, pendingconfirm);

    List<WebElement> tableValues = driver.findElements(By.xpath("//table//tr//td[contains(@class,'mat-column-demandId')]//span"));
    int tableValueSize = tableValues.size();
    System.out.println("Get the no of rows:" + tableValueSize);

    // 处理表格为空的边界场景
    if (tableValueSize == 0) {
        throw new RuntimeException("未在表格中查询到demandId数据");
    }

    // 调整顺序:先等待元素加载完成,再获取元素内容
    String targetXpath = "(//table//tr//td[contains(@class,'mat-column-demandId')]//span)[" + tableValueSize + "]";
    WebDriverWait wait = new WebDriverWait(driver, 30);
    WebElement latestIdEle = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(targetXpath)));

    String latestId = latestIdEle.getText().trim();
    System.out.println("Latest DemandIds: " + latestId);
    return latestId;
}

优化后的URL拼接逻辑

String confirmationURL = "https://test-webapp.net/#/type=confirm";
List<String> newurls = new ArrayList<>();

// 先调用方法获取ID,再做非空校验后拼接
String latestDataId = getid(driver);
if (latestDataId != null && !latestDataId.isEmpty()) {
    newurls.add(confirmationURL + "&id=" + latestDataId);
} else {
    throw new RuntimeException("获取ID为空,无法完成URL拼接");
}

如果必须保留静态HashMap存储逻辑,需要额外增加两处校验:

  1. 调用get()前先判断createdValue != null && createdValue.containsKey("latestDataId")
  2. put操作完成后校验存入的值非空,避免空值写入

内容的提问来源于stack exchange,提问作者sandy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 02:00:00