【发布时间】:2021-08-30 05:20:25
【问题描述】:
我有一个这样的列表
public static ImmutableList<House> HOUSES =
ImmutableList.of(
new House.WithName("first"),
new House.WithName("second"),
new House.WithoutPlace("third", 9400));
我有一种方法可以通过名称找到房子,但我希望它返回类类型而不是房子接口,例如当我执行findHouse("third") 我希望它返回House.WithoutPlace 而不是House,如何我能做到吗?
public static <T extends House> ImmutableList<T> findHouse(String name) {
return HOUSES.stream()
.filter(h -> h.name().equals(name))
.collect(toImmutableList());
// returns no instance(s) of type variable(s) exist
}
【问题讨论】:
-
“类类型”是什么意思?
-
@chrylis-cautiouslyoptimistic- 我在帖子示例中解释了当我确实 findHouse("third") 我希望它返回 House.WithoutPlace 而不是 House
-
它没有返回 either;它返回
House的instances(在本例中为House.WithoutPlace的实例)。实例是House.WithoutPlace的实例。 (如果您尝试更改返回 type,它不会那样工作,除非您 也 传入Class<T>并过滤两次。)