我似乎总是需要在 params 对象中强制转换值才能执行 .equals
但感觉总是不对。如果我使用 parseXXX
方法,我也必须在值为空时保护自己。似乎有更好的方法可以用像 Groovy 这样的动态语言来处理这个问题。有没有人找到一种感觉更像 Groovy 而不像 Java 的不同方式?我可以构建一个实用程序类来清理它,但我正在寻找一些内置功能,所以请不要建议额外的库。
例子:
def intValue = (params.intValue)? Integer.parseInt(params.intValue) :null
Things.each{ thing ->
if (thing.intValue.equals(intValue)){
//do stuff
}
}
最佳答案
使用 Type Conversion Methods 怎么样? :
def intValue = params.int('myparam')
...there are also methods for
boolean
,long
,char
,short
and so on. Each of these methods are null safe and safe from any parsing errors so you don't have to perform any addition checks on the parameters.
关于java - 一种更优雅的转换方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7045668/