繁体   English   中英

ClassCastException:java.lang.String无法强制转换为Ljava.lang.String

[英]ClassCastException: java.lang.String cannot be cast to Ljava.lang.String

我得到这个错误 - >

java.lang.ClassCastException: java.lang.String cannot be cast to [Ljava.lang.String; 

从下面粘贴的代码。

public class LoginAttemps extends Setup {
    public void testSearchCountry() throws Exception {
        driver.get("http://www.wikipedia.org/wiki/Main_Page");
        ReadExcelDemo readXls = new ReadExcelDemo();
         List dataList = readXls.getData();
         for (int i = 1; i < dataList.size(); i++) {
             String[] testCase = new String[5];
             String[] test = (String[]) dataList.get(i);
             String countryName = test[0];
             String countryDesc = test[1];
             driver.findElement(By.id("searchInput")).clear();
             driver.findElement(By.id("searchInput")).sendKeys(countryName);
             driver.findElement(By.id("searchButton")).click();
             String str = driver.findElement(
             By.xpath("//h1[@id='firstHeading']/span")).getText();
             System.out.println(countryDesc);
             Assert.assertTrue(str.contains(countryName));
         }
   }
}

我认为问题在于String[] test = (String[]) dataList.get(i);

但我不确定如何解决这个异常..任何线索?

您不能将“String”强制转换为“字符串数组”。

您只能将字符串放入数组中的插槽中。

你能做的是:

    String theString = "whatever";
    String[] myStrings = { theString };

查看代码,我相信您尝试将List转换为数组 ,因此您的“问题行”应如下所示:

String[] test = (String[]) dataList.toArray(new String[dataList.size]);

原因:“i”位置的元素是string类型。 但是,您尝试将其转换为字符串数组。

直接解决方案:从两侧移除[],即从以下位置更改:

String[] test = (String[]) dataList.get(i);

至:

String test = (String) dataList.get(i);

如果您的List不包含任何类型的数组,这将起作用。

感谢大伙们。 是的,我正在尝试将列表对象强制转换为字符串数组。 我找到了问题。 更正了代码。

    public void testSearchCountry() throws Exception {
        driver.get("http://www.wikipedia.org/wiki/Main_Page");
        ReadExcelDemo readXls = new ReadExcelDemo();
         List dataList = readXls.getData();
        String[] test = new String[dataList.size()];
         for (int i = 1; i < dataList.size(); i++) {
             String[] testCase = new String[5];
             test[i] = dataList.get(i).toString();
             String countryName = test[0];
             String countryDesc = test[1];
             driver.findElement(By.id("searchInput")).clear();
             driver.findElement(By.id("searchInput")).sendKeys(countryName);
             driver.findElement(By.id("searchButton")).click();
             String str = driver.findElement(
             By.xpath("//h1[@id='firstHeading']/span")).getText();
             System.out.println(countryDesc);
             Assert.assertTrue(str.contains(countryName));
         }
   }

它起作用了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM