public static boolean isNumeric(String str) { // 判断字符串是否为空或长度为0 if (str == null || str.length() == 0) { return false; } // 利用正则表达式判断是否为数字或小数 Pattern pattern = Pattern.compile("^(-?\\d+)(\\.\\d+)?$"); return pattern.matcher(str).matches(); }优化该方法 并显示引用的类
时间: 2024-03-01 19:53:50 浏览: 17
可以对该方法进行以下优化:
1. 使用 StringUtils 工具类的 isBlank() 方法来判断字符串是否为空或长度为0;
2. 将正则表达式的 Pattern 对象编译为静态常量,以便在多次调用该方法时重复利用。
优化后的代码如下:
```java
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
public class NumericUtils {
private static final Pattern NUMERIC_PATTERN = Pattern.compile("^(-?\\d+)(\\.\\d+)?$");
public static boolean isNumeric(String str) {
// 判断字符串是否为空或长度为0
if (StringUtils.isBlank(str)) {
return false;
}
// 利用正则表达式判断是否为数字或小数
return NUMERIC_PATTERN.matcher(str).matches();
}
}
```
在该代码中,我们引用了 Apache Commons Lang 库中的 StringUtils 工具类,使用其 isBlank() 方法来判断字符串是否为空或长度为0。同时,我们将正则表达式的 Pattern 对象编译为静态常量 NUMERIC_PATTERN,以便在多次调用该方法时重复利用,提高了代码的执行效率。