具有反关系的通用接口 - java

我想创建两个具有反向关系的接口。

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

我不确定表达式C extends Category<D,Item<D,C>>是否正确,但是至少没有编译器错误。

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

I extends Item给出警告Item is a raw type. References to Item<D,C> should be parametrized。我试过了

I extends Item<D,Category<D,I>>

但这会导致错误Bound mismatch: The type Category<D,I> is not a valid substitute for the bounded parameter <C extends Category<D,Item<D,C>>> of the type Item<D,C>。如何使用泛型正确设置接口Category的参数?

参考方案

这似乎有效:)。我不知道如何解释它(我通常会尽量避免做那样的事情),但是在这里:

interface Description {}

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

}

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

class DescriptionImpl implements Description {}

class CustomItem implements Item<DescriptionImpl, CustomItem, CustomCategory> {
    public CustomCategory getCategory() {
        return null;  
    }

    public void setCategory(CustomCategory category) {
    }
}

class CustomCategory implements Category<DescriptionImpl, CustomCategory, CustomItem> {

    public List<CustomItem> getItems() {
        return null;          }

    public void setItems(List<CustomItem> items) {
    }
}

现在,如果您这样做:

CustomCategory customCategory = new CustomCategory();
CustomItem customItem = new CustomItem();
DescriptionImpl description = new DescriptionImpl();

customItem.getCategory();

customItem.getCategory()返回的类别的类型是CustomCategory,我认为这是您真正想要的。

Java中的<<或>>>是什么意思? - java

This question already has answers here: Closed 7 years ago. Possible Duplicate: What does >> and >>> mean in Java?我在一些Java代码中遇到了一些陌生的符号,尽管代码可以正确编译和运行,但对于括号在此代码中的作用却感…

菱形运算符<>是否等于<?> - java

我在util.TreeSet类中发现,其中一个构造函数正在使用具有空泛型类型的新TreeMap调用另一个构造函数。 public TreeSet(Comparator<? super E> comparator) { this(new TreeMap<>(comparator)); } new TreeMap<>是什么意思…

通过Maven编译器插件不会发生有限的包含和排除 - java

我正在使用3.6.0版的maven编译器插件,在此我们只想在特定文件夹中编译一个文件,而在该位置编译所有其他文件。例如:在文件夹应用程序中有14个文件,从那我只希望编译1个文件,但它编译了所有文件,如果我要排除,则它也不起作用。 <sourceDirectory>${basedir}/../src/java</sourceDirectory…

与哪些运算符>>兼容 - java

我这里没有什么代码int b=3; b=b >> 1; System.out.println(b); 它可以完美工作,但是当我将变量b更改为byte,short,float,double时,它包含错误,但是对于变量int和long来说,它可以完美工作,为什么它不能与其他变量一起工作? 参考方案 位移位运算符(例如>>)与任何整数类型兼…

休眠映射<键,设置<值>> - java

我有以下表格:@Entity @Table(name = "events") Event --id --name @Entity @Table(name = "state") State --id --name @Entity @Table(name = "action") Action --id …