在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;
}
}
以上是幾種常見的封裝接口返回值的方法,具體的選擇可以根據實際需求和項目的架構來決定。