当我这样做时,我需要使用以前工作流程中的一个或多个输出为不同的工作流程构建一组输入
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/