gpt4 book ai didi

java - Constructor中如何处理Writer、Result、OutputStream?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:17:56 25 4
gpt4 key购买 nike

我有一个类封装了一个 StAX Writer 用于特殊的业务 XML 编写。您可以插入一些域对象,逻辑会生成足够的 XML。

出于安全原因,我不想提供 XMLStreamWriter 实例,因此此类是唯一负责写入此编写器的类。 XMLStreamWriter 将在此类中实例化。为了支持几乎所有的输出变体,例如 Result、OutputStream 和 Writer,我还为这些变体提供了构造。

public CustomStreamWriter ([...], Result result) {
this([...], (Object) result);
}

public CustomStreamWriter ([...], OutputStream outputStream) {
this([...], (Object) outputStream);
}

public CustomStreamWriter ([...], Writer writer) {
this([...], (Object) writer);
}

protected CustomStreamWriter ([...], Object outputHandler) {
// Initialize some final fields and do some stuff with [...]
XMLOutputFactory factory = XMLOutputFactory.newInstance();

if(outputHandler instanceof OutputStream) {
this.writer = factory.createXMLStreamWriter((OutputStream) outputHandler);
} else if(outputHandler instanceof Result) {
this.writer = factory.createXMLStreamWriter((Result) outputHandler);
} else if(outputHandler instanceof Writer) {
this.writer = factory.createXMLStreamWriter((Writer) outputHandler);
}
}

当我看到它时,我认为这是非常丑陋的,而且不是实现此目标的巧妙方法。 Stackoverflow,你对我有什么提示吗?

最佳答案

我会这样写。

public CustomStreamWriter ([...], Writer writer) throws XMLStreamException {
this([...], XMLOutputFactory.newInstance().createXMLStreamWriter(writer);
}

protected CustomStreamWriter ([...], XMLStreamWriter outputHandler) {
this.writer = writer;
}

如果构造函数抛出异常,构造函数无法处理它并创建一个有效的对象,因此抛出异常是一种明智的处理方式。

关于java - Constructor中如何处理Writer、Result、OutputStream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4519223/

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