在Java中,可以使用以下几种方式来封装接口的返回值:
示例代码:
public class Result {
private int code;
private String message;
// getter and setter methods
// other methods if needed
}
public interface MyInterface {
Result doSomething();
}
class MyClass implements MyInterface {
public Result doSomething() {
Result result = new Result();
result.setCode(200);
result.setMessage("Success");
return result;
}
}
示例代码:
public interface MyInterface {
Map<String, Object> doSomething();
}
class MyClass implements MyInterface {
public Map<String, Object> doSomething() {
Map<String, Object> result = new HashMap<>();
result.put("code", 200);
result.put("message", "Success");
return result;
}
}
示例代码:
public class Response<T> {
private int code;
private String message;
private T data;
// getter and setter methods
// other methods if needed
}
public interface MyInterface {
Response<String> doSomething();
}
class MyClass implements MyInterface {
public Response<String> doSomething() {
Response<String> response = new Response<>();
response.setCode(200);
response.setMessage("Success");
response.setData("Hello World");
return response;
}
}
以上是几种常见的封装接口返回值的方法,具体的选择可以根据实际需求和项目的架构来决定。