I'd like to merge this two methods using generics, the only difference are the casting classes "ServicesBO" and "ServicesDAO". The name of the bean can be passed as a string parameter. Is it possible to merge them using generics for the casting classes?
private void getFieldBO(){
ServicesBO services = (ServicesBO)appContext.getBean("ServicesBo");
List<users> list = services.getUsers();
for (users user: list)
System.out.println("BO: " + user.getName());
}
private void getFieldDAO(){
ServicesDAO services = (ServicesDAO)appContext.getBean("ServicesDAO");
List<users> list = services.getUsers();
for (users user: list)
System.out.println开发者_StackOverflow("DAO: " + user.getName());
}
Thanks in Advance Chuck.
Without a common interface that both ServicesDao and ServicesBO implement, you won't be able to call getUsers without reflection.
So assuming that you've got a common interface:
public interface UserProvider {
List<User> getUsers();
}
You can define the method as follows:
private void printUsers(String beanName) {
UserProvider provider = appContext.getBean(beanName, UserProvider.class);
List<User> users = provider.getUsers();
for (User user : users)
System.out.println("DAO:" + user.getName());
}
A couple of other things:
- usually class names start with uppercase (Users not users)
- class name should probably be User as the getName method suggests that the class only holds a single user
- I'd consider it better practice to use spring to inject beans rather than looking them up from the application context.
Hope that helps.
Whats wrong with plain polimorphysm?
Define an interface and implement it in the ServicesDao
and ServicesBO
public interface UserProvider{
List<users> getUsers();
}
Then you can
UserProvider services = (UserProvider)appContext.getBean(beanName);
List<users> list = services.getUsers();
for (users user: list){ /* do stuff with user*/}
The simple way to solve this is to have both of your service objects implement a common interface. Something like:
public interface UserSource {
List<users> getUsers();
}
Then you mark ServicesBO
and ServicesDAO
as implementing this interface, which allows you to do:
private void getFieldProvider(String providerName){
UserSource services = (UserSource)appContext.getBean(providerName);
List<users> list = services.getUsers();
for (users user: list)
System.out.println(providerName + ": " + user.getName());
}
The more complex way is to use Reflection, which allows you to do this without needing to provide an interface for the service objects to share. For example, you can do:
private void getFieldProvider(String providerName){
Object services = appContext.getBean(providerName);
List<users> list = Collections.emptyList();
try {
Method method = services.getClass().getMethod("getUsers");
list = (List<users>)method.invoke(services);
}
catch (Exception e) {
e.printStackTrace();
}
for (users user: list)
System.out.println(providerName + ": " + user.getName())
}
精彩评论