校验int为非空
时间: 2023-11-28 22:50:36 浏览: 56
在Java中,int是一种基本数据类型,它不能为null(空)。如果想要校验一个int是否为0或者为null,可以使用下面的代码:
```java
public boolean isNotNullOrZero(Integer number) {
return number != null && number != 0;
}
```
这个方法接收一个Integer类型的参数,并且判断这个参数是否为null或者为0。如果不是,则返回true,否则返回false。注意,这里使用的是Integer而不是int,因为int不能为null,而Integer可以为null。如果要校验一个int类型的变量是否为0,可以直接使用以下代码:
```java
public boolean isNotZero(int number) {
return number != 0;
}
```
这个方法接收一个int类型的参数,并且判断这个参数是否为0。如果不是,则返回true,否则返回false。
相关问题
Java校验参数工具类,包括长度、非空、正则、分组校验
好的,以下是一个Java校验参数工具类的示例,实现了长度、非空、正则、分组校验:
```java
import java.util.regex.Pattern;
public class ParamValidator {
/**
* 校验字符串长度是否在指定范围内
* @param str 字符串
* @param min 最小长度
* @param max 最大长度
* @return 校验结果
*/
public static boolean checkLength(String str, int min, int max) {
if (str == null) {
return false;
}
int len = str.length
GO 参数校验
在 Go 中,可以使用结构体的 tag 来进行参数校验。我们可以使用第三方库,如 go-validator、go-playground/validator 等。这些库都提供了丰富的校验规则,如非空、长度、正则表达式匹配等等。我们可以在结构体定义中使用 tag 来定义校验规则,例如:
```go
type User struct {
Name string `validate:"required,min=2,max=20"`
Age int `validate:"required,gte=18"`
Email string `validate:"required,email"`
Password string `validate:"required,min=6"`
}
```
以上定义表示 Name 字段必须非空且长度在 2 到 20 之间,Age 字段必须非空且大于等于 18,Email 字段必须非空且符合 email 格式,Password 字段必须非空且长度不小于 6。可以使用 validate.Struct(user) 来对 User 结构体进行校验。
当然,我们也可以自定义校验规则,只需要实现 validator.Funcs 方法即可。这样,我们就可以方便地进行参数校验了。
相关推荐
![js](https://img-home.csdnimg.cn/images/20210720083646.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)