java 写一个全局统一返回类
时间: 2024-05-04 22:20:42 浏览: 19
好的,以下是一个 Java 实现的全局统一返回类,包含了常用的返回信息:
```java
public class Result<T> {
private int code;
private String message;
private T data;
public Result(int code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
public Result(int code, String message) {
this(code, message, null);
}
public Result(T data) {
this(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), data);
}
public Result() {
this(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), null);
}
// 省略 getter 和 setter 方法
}
```
上面的 `Result` 类使用了泛型,可以用于返回任意类型的数据。其中,`code` 表示返回码,`message` 表示返回信息,`data` 表示返回的数据。同时,还提供了多个构造函数,方便使用。
使用示例:
```java
@RestController
public class DemoController {
@GetMapping("/data")
public Result<List<String>> getData() {
List<String> dataList = new ArrayList<>();
dataList.add("data1");
dataList.add("data2");
return new Result<>(dataList);
}
@GetMapping("/error")
public Result<String> getError() {
return new Result<>(HttpStatus.INTERNAL_SERVER_ERROR.value(), "服务器异常");
}
}
```
以上代码演示了如何在控制器中使用 `Result` 类进行返回。通过构造函数,可以方便地创建返回对象,并在需要时返回相应的数据和信息。
相关推荐
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)