gpt4 book ai didi

java - 返回泛型列表时转换对象

转载 作者:行者123 更新时间:2023-12-01 14:20:45 27 4
gpt4 key购买 nike

我对 Java 和泛型比较陌生。我试图了解我在编写通用方法时是否做错了什么。我有以下代码(大大简化):

public class ContentIniter {       
public ContentType getContentType();
}

public interface Content {
}

public class Show implements Content {
}

public class Movie implements Content {
}

public enum ContentType {
Movie, Show
}

public class Channel {

public List<Show> getShows() {
return getContentByType(ContentType.Show)
}

public List<Movie> getMovies() {
return getContentByType(ContentType.Movie)
}

private <T> List<T> getContentByType(ContentType contentType) {
List<T> typeContents = Lists.newArrayList();
List<ContentIniter> allContentIniters = someMethod(); // Returns initers for both shows and movies
for (Content contentIniter : allContentIniters) {
if (contentIniter.getContentType().equals(contentType)) {
switch (contentType) {
case Movie:
typeContents.add((T) new Movie(contentIniter));
break;
case Show:
typeContents.add((T) new Show(contentIniter));
break;
}
}
}
return typeContents;
}

}

我的问题与以下行有关:

typeContents.add((T) new Movie(contentIniter));

我能够编译代码的唯一方法是将内容对象转换为 T。但这对我来说似乎很恶心(而且我不明白为什么编译器不能推断基于类型关于通话)。此外,即使代码可以工作,IntelliJ 也会提示未经检查的强制转换。

有没有更好的方法来编写泛型方法?

更新:当我试图简化代码时,代码有点困惑。修复了对 typeContents 的引用。另外,我添加了更多的复杂性,以便它更好地反射(reflect)现实,希望解释为什么我不简单地检查 instanceof

更新 2:意识到还有另一个错误...ContentIniter 未实现内容。还值得注意的是,ContentIniter 只是一个虚构的对象。如果看起来很奇怪,请将其视为内容对象用来委托(delegate)某些行为的事件或其他策略。

最佳答案

您没有正确使用泛型,当确实没有必要时,您将它们与枚举混合在一起。理想情况下,您应该调用 getContentByType<Show>()然后从 allContents 中确定正确类型的列表使用反射。

尝试更多类似的事情(未经测试):

private <T> List<T> getContents() {
List<T> typeContents = Lists.newArrayList();
List<Content> allContents = someMethod(); // Returns both shows and movies
for (Content content : allContents) {
if (content instanceof T) {
typeContents.add((T) content);
}
}
return typeContents;
}

并调用:

List<Show> shows = getContents<Show>();

然后,您可以将对其调用的类型限制为仅扩展 Content 的类型.

private <T extends Content> List<T> getContents() {
...
}

关于java - 返回泛型列表时转换对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17585052/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com