简体   繁体   English

Java泛型问题

[英]Java Generics Question

I have following list of users. 我有以下用户列表。 StudentBean and ProfessorBean are the subtypes of UsersBean. StudentBean和ProfessorBean是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. 在这里,我想打印professorbean的信息或StudentBeans的信息。 Is there any way to get professor or student bean methods without explicit cast ? 有没有办法在没有明确演员的情况下获得教授或学生bean方法?

If the method is common and is declared in base class or interface ( UsersBean ), yes. 如果该方法很常见并且在基类或接口( UsersBean )中声明, UsersBean yes。 Otherwise - no, you need to cast. 否则 - 不,你需要施放。 No duck typing in Java. 没有用Java打字的鸭子。

You need to declare the methods you want to access in the UserBean class/interface. 您需要在UserBean类/接口中声明要访问的方法。 For example if UserBean is an interface you would have: 例如,如果UserBean是您将拥有的接口:

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

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" 并且,它与“泛型”无关

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. 如果您的集合需要访问bean方法,则需要将UserBean对象强制转换为StudentBean或ProfessorBean。

Common methods could be declared as abstract getters/setters in the UserInfo bean to avoid casting. 可以在UserInfo bean中将常用方法声明为抽象getter / setter以避免强制转换。

An alternative could be overloading the getUser Method to allow filtering like this: 替代方法可能是重载getUser方法以允许这样的过滤:

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. 它仍然需要强制转换,但是铸造将在getUser方法中“隐藏”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM