我将在底部发布我的问题。
下面是其他类扩展的类。
public class people {
class family extends people {
}
class friends extends people {
}
class coworkers extends people {
}
}
下面是具有 getAllPeopleByClass 方法的类,该方法由选择类中的 getMembers() 方法调用:
public class processing {
static processing process = null;
private Collection<family> familyList = new ArrayList<family>();
private Collection<coworkers> cowList = new ArrayList<coworkers>();
private Collection<friends> friendList = new ArrayList<friends>();
public processing(){
}
public static processing getInstance() {
if (process == null)
process = new processing();
return process;
}
public <T> Collection<people> getAllPeopleByClass(Class<T> clazz) {
Collection<people> peopleCollection;
peopleCollection.addAll(getList(clazz));
return peopleCollection;
}
private <T> Collection<? extends people> getList(Class<T> clazz) {
if (clazz == family.class) {
return familyList;
} else if (clazz == coworkers.class) {
return cowList;
} else { // else if clazz == friends.class
return friendList;
}
}
最后,使用处理的类:
public class familySelection {
public Collection<family> getMembers() {
Collection<family> f;
f = processing.getInstance().getAllPeopleByClass(family.class); //type mismatch
return f;
}
}
public class coworkerSelection {
public Collection<coworkers> getMembers() {
Collection<coworkers> c;
c = processing.getInstance().getAllPeopleByClass(coworkers.class); //type mismatch
return c;
}
}
public class friendsSelection {
public Collection<friends> getMembers() {
Collection<friends> f;
f = processing.getInstance().getAllPeopleByClass(friends.class); //type mismatch
return f;
}
}
我的问题是我从每个 getMembers() 方法中的 getAllPeopleByClass 调用中得到类型不匹配。
我试过这个:
public class familySelection {
public Collection<family> getMembers() {
Collection<? extends people> f; //changed to extend from people
f = processing.getInstance().getAllPeopleByClass(family.class);
return (Collection<family>) f; //cast warning - dont want that
}
}
这行得通,但我得到一个演员警告,我不想也不想压制它。这是我最接近解决问题的方法。此外,getMembers() 的返回类型必须保持不变。有没有人有办法在没有任何警告的情况下做到这一点?或者甚至以某种方式一般地处理这个?谢谢!