【问题标题】:cannot convert from String to Integer无法从字符串转换为整数
【发布时间】:2014-02-26 09:55:43
【问题描述】:

我已经实现了一些运行良好的服务。该服务具有以下属性:

 @Property(name = MyService.PROXY_PORT, label = "Proxy Port", description = "Proxy Port", value= "8080")
    private static final String PROXY_PORT = "proxy.port";

我得到port属性的值如下:

..
...
properties = context.getProperties();
String port = properties.get(PROXY_PORT).toString();
...

port 在这种情况下产生8080。现在我想将此字符串转换为整数。我尝试了以下方法:

int portInt = Integer.parseInt(port);
int portInt2 = Integer.getInteger(port);

两个结果都为空:(

我做了什么?

【问题讨论】:

  • port 是否有价值?
  • int怎么可以为null
  • System.out.println("**"+port+"**"); 放在int portInt = Integer.parseInt(port); 之前并告诉我们输出结果。
  • 检查你是否获得了端口值。并检查你得到什么异常?是numberFormat吗?还是它的 nullPointer?
  • 检查字符串是否为空,如果不为空,则修剪其空间。

标签: java aem apache-felix


【解决方案1】:

考虑使用PropertiesUtil,一个专门为此案例创建的实用程序类:

int port = PropertiesUtil.toInteger(properties.get(PROXY_PORT), 8080);

第二个参数是默认值。

【讨论】:

    【解决方案2】:

    如果端口有值且不为空,则尝试:

    int portInt = Integer.valueOf(port.trim());
    

    【讨论】:

      【解决方案3】:

      试试看是否可行:

      int portInt = Integer.parseInt(port+""); // check if the port value is coming or not before parse it.
      int portInt2 = Integer.getInteger(port+"");
      

      【讨论】:

      • 同意,但这可能是一个案例,我也遇到了同样的问题,字符串解析......所以我尝试这种方式并且它正在工作
      • 这会产生一个稍微不同的异常(如果我们有异常,OP没有告诉我们),但不能解决问题。
      猜你喜欢
      • 2018-08-04
      • 1970-01-01
      • 2012-10-22
      • 2016-02-24
      • 2015-03-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多