I need to create some kind of response wrapper (in Rest controller). All mappings should return some necessary fields and some field specific to each class.
For example I have a mapping that returns list of objects of class User
and one that returns a list of objects of type Account
. Result is always of type List
(that I'm getting from JdbcTemplate
) because it could contain more that one User/Account:
public class User {
private String name;
private String jobTitle;
// constructor, getters, setters
}
public class Account {
private String id;
private String type;
// constructor, getters, setters
}
And I have a wrapper:
public class Wrapper {
public String requestDate;
public String result;
public List<?> resultObject; // should be User or Account
// constructor, getters, setters
}
How can I make it possible to create an instance of wrapper like this:
//suppose I have a List of User objects called myUserList;
Wrapper wrapper = new Wrapper(today, "success", User.class, myUserList);
It looks similar to Spring's BeanPropertyRowMapper<T>
but I stucked on implementing such for me.
i don't know if i correctly understood your question but you can use generics in this way
public class Wrapper<T> {
public String requestDate;
public String result;
public List<T> resultObject;
// constructor, getters, setters
}
As yuo can see you defined wrapper in a "generic way"; now everytime you build a wrapper instance you can specify a class; for example if you want to create a wrapper of User:
List<User> myUserList = new ArrayList<User>();
Wrapper<User> usrWrap = new Wrapper(today, "success", myUserList);
I hope it is usefull
Angelo
What about using something like this:
Wrapper abstract class:
public abstract class Wrapper {
public String requestDate;
public String result;
// constructor, getters, setters
}
User Wrapper class:
public class UserWrapper extends Wrapper {
public List<User> resultObject;
// constructor, getters, setters
}
Account Wrapper class:
public class AccountWrapper extends Wrapper {
public List<Account> resultObject;
// constructor, getters, setters
}
Consumption:
UserWrapper userWrapper = new Wrapper(today, "success", myUserList);
AccountWrapper accountWrapper = new Wrapper(today, "success", myAccountList);
List<Wrapper> wrapperList = Array.asList(userWrapper, accountWrapper);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.