1

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 ?

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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"

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.