Java类型参数是隐藏一个泛型

Java类型参数是隐藏一个泛型

本文介绍了Java类型参数是隐藏一个泛型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个泛型类:

  public class Widget< COMMAND> {
// ...
}

所以我可以创建实例它就像:

  Widget< Fizz> fizzWidget = new Widget< Fizz>(); 

然后我有一个ABC BaseWidgetProcessor ,那我想接受任何类型的 Widget s:

  public abstract class BaseWidgetProcessor< ;窗口小部件<指挥GT;> {
public abstract COMMAND process();
}

使用具体的impls:

  public abstract class AstroWidgetProcessor< Widget< COMMAND>> {
@Override
public COMMAND process(){
// ...
}
}

etc。

问题是,使用 BaseWidgetProcessor

  public abstract class BaseWidgetProcessor< Widget< COMMAND>> {
public abstract COMMAND process();
}

我得到一个语法错误:

当我将其更改为:

  public abstract class BaseWidgetProcessor< Widget> {
public abstract COMMAND process();
}

错误消失了,但现在我得到一个编译器警告:

这里发生了什么?!?为什么错误,然后各自的警告?什么是正确的(语法)设置方法?

解决方案

我认为你在寻找的是:

  public abstract class BaseWidgetProcessor< W extends Widget< C>,C> {
public abstract C process(W widget);
}

我添加了 W小部件作为参数来显示更好的用法。



现在假设您有一个名为CoolWidget的窗口小部件:

  public class CoolWidget扩展Widget< Integer> {bb} {/ code> 

要声明一个CoolWidgetProcessor,您必须这样做:

  public class CoolWidgetProcessor扩展BaseWidgetProcessor< CoolWidget,Integer> {
@Override
public Integer process(CoolWidget widget){
// ...
}
}


I have a generic class:

public class Widget<COMMAND> {
    // ...
}

So I can create instances of it like:

Widget<Fizz> fizzWidget = new Widget<Fizz>();

Then I have an ABC BaseWidgetProcessor, that I want accepting Widgets of any type:

public abstract class BaseWidgetProcessor<Widget<COMMAND>> {
    public abstract COMMAND process();
}

With concrete impls:

public abstract class AstroWidgetProcessor<Widget<COMMAND>> {
    @Override
    public COMMAND process() {
        // ...
    }
}

etc.

The problem is, with BaseWidgetProcessor:

public abstract class BaseWidgetProcessor<Widget<COMMAND>> {
    public abstract COMMAND process();
}

I get a syntax error:

When I change it to:

public abstract class BaseWidgetProcessor<Widget> {
    public abstract COMMAND process();
}

The error goes away, but now I get a compiler warning:

What is going on here?!? Why the error and then respective warning? What's the correct (syntactically) way to set this up?

解决方案

I think what you are looking for is:

public abstract class BaseWidgetProcessor<W extends Widget<C>, C> {
    public abstract C process(W widget);
}

I added W widget as argument to show a bit better the usage.

Now let's say that you have a widget named CoolWidget:

public class CoolWidget extends Widget<Integer> {}

To declare a CoolWidgetProcessor you would have to do:

public class CoolWidgetProcessor extends BaseWidgetProcessor<CoolWidget, Integer> {
    @Override
    public Integer process(CoolWidget widget) {
        // ...
    }
}

这篇关于Java类型参数是隐藏一个泛型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 12:16