Zeeshan
Zeeshan

Reputation: 1173

Java Generics Question

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 ?

Upvotes: 1

Views: 109

Answers (4)

krock
krock

Reputation: 29619

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";
    }
}

Upvotes: 2

Andreas Dolk
Andreas Dolk

Reputation: 114757

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.

Upvotes: 0

Adrian Shum
Adrian Shum

Reputation: 40036

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"

Upvotes: 0

Konrad Garus
Konrad Garus

Reputation: 54005

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.

Upvotes: 2

Related Questions