写一个通用的返回结果类,类名为CommonResult,需要包含什么属性,要能够.failed
时间: 2024-05-02 19:16:28 浏览: 10
好的,以下是一个通用的返回结果类 CommonResult 的代码实现,其中包含了 code、message、data 三个属性:
```java
public class CommonResult<T> {
private Integer code;
private String message;
private T data;
public CommonResult() {
}
public CommonResult(Integer code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
public static CommonResult success() {
return new CommonResult(200, "操作成功", null);
}
public static <T> CommonResult<T> success(T data) {
return new CommonResult<>(200, "操作成功", data);
}
public static CommonResult failed() {
return new CommonResult(500, "操作失败", null);
}
public static CommonResult failed(String message) {
return new CommonResult(500, message, null);
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
```
其中,success() 方法表示操作成功,failed() 方法表示操作失败,如果需要自定义失败信息,可以使用 failed(String message) 方法。使用示例:
```java
CommonResult<String> result = CommonResult.success("操作成功");
if (result.failed()) {
System.out.println(result.getMessage());
}
```
注意:这里使用了泛型 T,可以根据实际需求进行修改。