java - 将 1 传递给多个相同对象类型的参数

标签 java generics netbeans overriding variadic-functions

当我这样做时,我需要使用以前工作流程中的一个或多个输出为不同的工作流程构建一组输入

public interface InputBuilder<I extends SwfInput, O extends SwfOutput> {

    public I buildInput(O... output);
}


public class SwfAuthorisationInputBuilder implements InputBuilder {

    @Override
    public SwfAuthorisationInput buildInput(SwfOutput swfEventInitOutput) {

        SwfEventInitOutput output = (SwfEventInitOutput ) swfEventInitOutput;
        SwfAuthorisationInput authorisationInput = oddFactory.newInstance(SwfAuthorisationInput.class);
        authorisationInput.setNetworkEvent(output.getNetworkEvent());

        return authorisationInput;
    } 

我遇到了错误,Netbeans 提示修复给了我这个。我在这里做错了什么?

  @Override
        public SwfInput buildInput(SwfOutput... output) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

这是准确的错误

method does not override or implement a method from a supertype

我怎样才能避免在这里转换?

  @Override
        public SwfAuthorisationInput buildInput(SwfOutput... output) {
            SwfEventInitOutput swfEventInitOutput = (SwfEventInitOutput ) output[0];
            SwfLocationDetectionOutput swfLocationDetectionOutput = (SwfLocationDetectionOutput) output[1];


            SwfAuthorisationInput authorisationInput = oddFactory.newInstance(SwfAuthorisationInput.class);
            authorisationInput.setNetworkEvent(swfEventInitOutput.getNetworkEvent());

            return authorisationInput;
        }

最佳答案

buildInput(SwfOutput swfEventInitOutput)

buildInput(SwfOutput... swfEventInitOutput)

是不同的方法签名(Java 中的方法名称和参数类型)。如果你想重写一个方法,你必须完全 * 指定来自父类的签名。


如我所见,您只需要这个数组的一个元素。如果是这样,您可以从数组中取出它,然后检查数组的大小:

swfEventInitOutput element = swfEventInitOutput.length > 0 ? swfEventInitOutput[0] : null;
if(element != null) { ... }

另一种方法是遍历数组并对每个元素执行这样的操作:

for (swfEventInitOutput element : swfEventInitOutput) { ... }

此外,我建议您在实现 InputBuilder 接口(interface)时指定泛型类型。它可以帮助您避免在重写的方法中进行强制转换(您已经这样做了)。

这里的积极方面是您使用了有界泛型类型,它阻止了Object...(或Object[])。

关于java - 将 1 传递给多个相同对象类型的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39768434/

相关文章:

java - Netbeans 中的 J2me : How can I align my list items from right to left?

java - 为什么我的 Maven Surefire 插件被忽略?

java - 如何识别并纠正边界框问题?

java - 如何在 hadoop 的单节点集群中运行 Java 程序?我是否需要将我的 java 代码转换为 JAR 文件然后执行?

java - 紧凑的 java.util.Map 实现

java - Java 如何检查一个值是否存在于数组中?

java - 泛型类型函数的返回语句错误

generics - 保持部分应用的函数通用

c# - C# 中的动态和泛型

java - 有人用条纹框架试过 scala