gpt4 book ai didi

java - 使用通用接口(interface)进行类转换而不发出警告

转载 作者:行者123 更新时间:2023-11-30 04:04:21 25 4
gpt4 key购买 nike

假设我们想要用 DescriptionItems 列表来描述一个 Category。每个 Item 也有一个 Category:

public interface Description
{
}

这个界面非常简单。使用通用边界描述类别变得更加复杂,但这不是火箭工程。

interface Category<D extends Description,
C extends Category<D,C,I>,
I extends Item<D,C,I>>
{
public List<I> getItems();
public void setItems(List<I> items);

public D getDescription();
public void setDescription(D description);
}

interface Item<D extends Description,
C extends Category<D,C,I>,
I extends Item<D,C,I>>
{
public C getCategory();
public void setCategory(C category);
}

现在我想定义一个接口(interface)来对对象进行类转换(SecretDescriptionDescription 的实现):

SecretDescription sd = new SecretDescription();
Description d = (SecretDescription)sd;

这当然有效,但现在的问题是:如何在不发出警告的情况下使用Category

Category c;

这给了我警告:

Category is a raw type. References to generic type Category<D,C,I>
should be parameterized

好的,但是我如何参数化它?

Category<Description,Category,Item> c;

这给了我编译器错误:

Bound mismatch: The type Category is not a valid substitute for the
bounded parameter <C extends Category<D,C,I>> of the type Category<D,C,I>

最佳答案

SecretDescription sd = new SecretDescription();
Description d = (SecretDescription)sd;

请不要在第二行进行不必要的转换。

Category<Description,Category,Item> c;

C参数有一个约束:它必须至少为 Category< D, C, I > 。原始类型Category不符合该限制,因此出现此消息。

当您使用这样的自限类型时,您必须创建至少一个在泛型参数中引用自身的子类或子接口(interface),以终止看似无限的回归。

interface ExampleCategory extends Category< Description, ExampleCategory, ExampleItem >{}
interface ExampleItem extends Item< Description, ExampleCategory, ExampleItem > {}

请注意,一旦将参数设置为某些内容,删除意味着您无法将其重置为层次结构中更深层次的其他内容:

// causes a compile error
interface BetterExampleCategory
extends ExampleCategory, Category< Description, BetterExampleCategory, ExampleItem > {}

也就是说,尽管我在 @rgettman 的回答中发表了评论,但您最好保留这些参数,直到您拥有一个具体的类,如

interface ExampleCategory< C extends ExampleCategory< C, I >, I extends ExampleItem< C, I > > extends Category< Description, C, I > {}
interface BetterExampleCategory< C extends BetterExampleCategory< C, I >, I extends ExampleItem< C, I > > extends ExampleCategory< C, I > {}

这可能会导致一些非常棘手的代码。 (如果您需要它来保证类型安全,那就这样做。Java 有时没有更好的答案。)

关于java - 使用通用接口(interface)进行类转换而不发出警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21120304/

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