简体   繁体   English

在Java中将参数传递给具有泛型的方法

[英]passing arguments to method with generics in java

I have the following structure of classes and methods : 我有以下类和方法的结构:

public class NavigationTree<T extends BaseListItem<? extends BaseData>> {
    public boolean insert(final T parent, final T child){
    }
}

public class Screen extends BaseData {
}

public class DrawerListItem<T> extends BaseListItem<T>{
}

This is what I am calling from one of my other classes : 这是我从其他班级之一打电话来的内容:

mCurItems.insert(new DrawerListItem<Screen>(null, null),
                 new DrawerListItem<Screen>(screen.name, screen));

The compilers throws the following error : 编译器将引发以下错误:

Error: incompatible types: DrawerListItem cannot be converted to CAP#1 where CAP#1 is a fresh type-variable:CAP#1 extends BaseListItem from capture of ? 错误:类型不兼容:DrawerListItem无法转换为CAP#1,其中CAP#1是一个新的类型变量:CAP#1从捕获到的扩展BaseListItem? extends BaseListItem 扩展BaseListItem

I do not understand why this should be wrong. 我不明白为什么这应该是错误的。 DrawerListItem extends BaseListItem and Screen extends BaseData . DrawerListItem extends BaseListItemScreen extends BaseData I have tried reading the other posts around generic types and type params but none of them seem to address this issue. 我尝试阅读其他有关泛型类型和类型参数的文章,但似乎都没有解决这个问题。

Try this: 尝试这个:

public class Test {
    public static void main(String[] args) throws java.lang.Exception {
        NavigationTree<DrawerListItem<Screen>> nt = new NavigationTree<>();
        nt.insert(new DrawerListItem<Screen>(), new DrawerListItem<Screen>());
    }

    private static class NavigationTree<T extends BaseListItem<? extends BaseData>> {
        public boolean insert(final T parent, final T child) {
            return true;
        }
    }

    private static class DrawerListItem<T> extends BaseListItem<T> {}
    private static class BaseListItem<T> {}
    private static class Screen extends BaseData {}
    private static class BaseData {}
}

I figured out the solution. 我想出了解决方案。 In my DrawerListItem declaration I had declared it as 在我的DrawerListItem声明中,我已将其声明为

public class DrawerListItem<T> extends BaseListItem<T>{
}

Whereas the NavigationTree was expecting: 而NavigationTree期望:

<T extends BaseListItem<? extends BaseData>>

Which essentially means : 实质上意味着:

<DrawerListItem<? extends BaseData>>

in this case. 在这种情况下。

And hence the error was basically saying that the template type declared vs template type required are different and hence the error. 因此,该错误基本上是说声明的模板类型与所需的模板类型不同,因此是错误。 Hope this helps someone else. 希望这对其他人有帮助。 Thanks everyone for the help! 谢谢大家的帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM