gpt4 book ai didi

java - 方法重载无法按预期使用 Java 泛型

转载 作者:行者123 更新时间:2023-11-30 08:29:30 24 4
gpt4 key购买 nike

我有一个泛型类:

public class Facet<C extends Component>
{
private final C child;

public Facet(C child) { this.child = child; }

public C getChild() { return this.child; }

public UIComponent getViewComponent() {
return PrimeFacesComponentFactory.create(facesContext, this.getChild());
}
}

我有一个组件工厂,它也有一堆方法,其中几个看起来像这样:

public static UIComponent create(FacesContext fc, Component component) {
throw new UnsupportedOperationException("Method not yet implemented for class: " + component.getClass().getName());
}

public static UIRow create(FacesContext fc, Row modelRow) { ... }

public static UIColumn create(FacesContext fc, Column modelColumn) { ... }

注意:在每个工厂方法中,第二个参数是一个扩展 Component 的对象,返回的始终是 UIComponent 的子类。第一个工厂方法(抛出异常的方法)旨在成为“全部捕获”,如果没有为特定组件编写的特定工厂方法,则会调用它。

我想做的是:应该根据子组件方面的类型调用正确的工厂方法。发生的情况是第一个工厂方法总是被调用(例如,抛出异常的方法)。这对我来说是违反直觉的,因为 C 的类型在运行时是已知的,并且 C 是“扩展 Component 的某种特定类型”。

调试时,我在Facet#getViewComponent 设置了一个断点,当我知道facet.getChild() 会返回一个Row 类型的对象时调用它。所以在这个例子中 C 是行。令我惊讶的是,当工厂方法被调用时,例如

PrimeFacesComponentFactory.create(facesContext, facet.getChild());

程序执行流向“catch all”工厂方法!但是,如果我按如下方式显式转换 facet.getChild():

PrimeFacesComponentFactory.create(facesContext, (Row)facet.getChild());

然后调用了特定的方法。很奇怪,因为我只是/冗余地将一行转换为一行。

我读过 some about why this is happening , 但在我看来它仍然是模糊的和违反直觉的。无论如何,我该如何解决这个问题?

最佳答案

对于 Facet,重载决议在编译时发生一次类,不是每个CFacet<C> ,而不是在运行时。一个潜在的解决方案是使您的 catch-all 方法更智能:

public static UIComponent create(FacesContext fc, Component component) {
if (component instanceof Row)
return create(fc, (Row)component);
else if (component instanceof Column)
return create(fc, (Column)component);
// include other types, and lastly
else
throw new UnsupportedOperationException("Method not yet implemented for class: " + component.getClass().getName());
}

关于java - 方法重载无法按预期使用 Java 泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19387869/

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