gpt4 book ai didi

java - 扩展不止一种类型的泛型

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

将扩展类并同时实现接口(interface)的对象分配给变量。我有一个这样的方法

public static <T extends Component & MyInterface> T instance() {
if (test1) return new MyLabel();
if (test2) return new MyCombo();
if (test3) return new MyText();
}

class MyLabel extends JLabel implements MyInterface {
...
}

class MyCombo extends JComboBox implements MyInterface {
...
}

class MyText extends JTextField implements MyInterface {
...
}

这意味着instance()返回的对象是一个Component并且实现了MyInterface。我可以做类似的事情

instance.setEnable(true); // calling a Component method
instance.foo(); // calling a MyInterface method

现在我想将返回值分配给一个变量:如何声明该变量以便为该变量带来所有泛型信息?

我希望能够做这样的事情:

static <T extends Component & MyInterface> T myVar = instance();
myVar.setEnable(true); // calling a Component method
myVar.foo(); // calling a MyInterface method

还有这个:

static void f1(Component c) {}
static void f2(MyInterface c) {}
f1(myVar);
f2(myVar);

在我看来,这个问题与Why can't I use a type argument in a type parameter with multiple bounds?中的问题不同。因为我没有在泛型类声明中使用类型参数。

最佳答案

根据约翰·博林格的建议,我做了一些其他实验并找到了一个可能的“解决方案”(但不像我要求的那么简单)。但我认为我的wrap()方法与John的意思不同。

public final class Wrap<X extends Component & MyInterface> {
public final X x;
public Wrap(X x) {
this.x = x;
}
}
public static <X extends Component & MyInterface> Wrap<X> wrap(X x) {
return new Wrap<X>(x);
}

static Wrap<?> myVar = wrap(instance());
myVar.x.setEnabled(true); // Component method
f1(myVar.x); // Component parameter
myVar.x.foo(); // MyInterface method
f2(myVar.x); // MyInterface parameter

关于java - 扩展不止一种类型的泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57359351/

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