tags:

views:

77

answers:

4

Hi, I have following list of users. StudentBean and ProfessorBean are the subtypes of UsersBean.

List<? extends UsersBean> users = this.getUsers(locationId);
for(UsersBean vo :users) { System.out.println("Name : "); }

Here i want to print professorbean's info OR StudentBeans's info. Is there any way to get professor or student bean methods without explicit cast ?

+2  A: 

If the method is common and is declared in base class or interface (UsersBean), yes. Otherwise - no, you need to cast. No duck typing in Java.

Konrad Garus
+2  A: 

You need to declare the methods you want to access in the UserBean class/interface. For example if UserBean is an interface you would have:

public interface UserBean {
    public String getInfo();
}

class StudentBean implements UserBean {
    public String getInfo() {
        return "student info";
    }
}

class ProfessorBean implements UserBean {
    public String getInfo() {
        return "professor info";
    }
}
krock
A: 

It sounds to me that is a smell of bad design.

You have a reference to User then you are suppose to "work on" User.

And, it is nothing to do with "Generics"

Adrian Shum
A: 

No, that's not possible. You need to cast the UserBean object to StudentBean or ProfessorBean if your collection you need to access bean methods.

Common methods could be declared as abstract getters/setters in the UserInfo bean to avoid casting.

An alternative could be overloading the getUser Method to allow filtering like this:

List<ProfessorBean> professors = this.getUser(locationId, ProfessorBean.class);

That method would just return the users that are profs (in this example). It would still require casting, but the casting would be 'hidden' in the getUser method.

Andreas_D