2014-02-26 48 views
0

我已经实现了一些可以正常工作的服务。该服务具有以下属性:不能从字符串转换为整数

@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。现在我想将这个String转换为Integer。我试过如下:

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

两个结果无效:(

我做了什么拨错

+3

'port'有价值吗? – ItachiUchiha

+7

int如何为null –

+2

把'System.out.println(“**”+ port +“**”);'int portInt = Integer.parseInt(port);'告诉我们输出。 – StephaneM

回答

1

如果端口具有价值和不为空然后尝试:

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

尝试,如果它的工作:

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

为什么这个工作和简单的使用端口不 – Mark

+0

同意男人,但它可能是一种情况,同样的问题发生在我身上,与字符串解析...所以我试试这种方式,它工作 –

+0

这将产生一个稍微不同的例外(如果我们有一个例外,OP没有告诉我们),但没有解决问题。 –

3

考虑使用PropertiesUtil,恰好对于这种情况下创建的工具类:

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

第二个参数是默认值。