我正在设计一个jax-rs应用程序。我需要为每个api调用都有一个共同的响应对象。这是它的模型。应修改UserObject变量以接受我使用get / set&rsrs设置的任何类。目前它只能接受Customer类。我需要这个变量才能接受客户,地址,员工.....(我通过的任何事情)。我该怎么办?
public class CustomResponse {
private Customer UserObject;
private String Attributes;
private String Tags;
....
}
答案 0 :(得分:3)
您可以使用泛型类:
public class CustomResponse<T> {
private T userObject;
private String Attributes;
private String Tags;
//a setter...
public void setUserObject(T object) {this.userObject = object;}
public T getUserObject() {return this.userObject;}
}
特定对象类型可以构造为:
CustomResponse<Customer> customerResponse = new CustomResponse<Customer>();
customerResponse.setUserObject(new Customer());
...
使用不同的资源方法:
CustomResponse<Address> customerResponse = new CustomResponse<Address>();
customerResponse.setUserObject(new Address());
...
答案 1 :(得分:2)
您可以在所需对象上实现接口,而不是Customer类,在响应中使用此特定接口:
public class CustomResponse {
private ResponseObject responseObject;
private String Attributes;
private String Tags;
...
}
然后在您的界面中,您可以拥有所有类中必须具有的方法的签名:
public interface ResponseObject {
...
}
然后,您的客户也是一个ResponseObject
public class Customer implements ResponseObject {
...
}