Why does Throwable.printStackTrace takes a PrintWriter, instead of a Writer?
-
01-07-2021 - |
Frage
Why does public void printStackTrace(PrintStream s)
in the Throwable class take a PrintWriter, instead of a Writer?
I think Writer should be the norm (code to the interface, not a specific implementation), but it could be something that I'm missing, hence this question.
Lösung
Writer
is an abstract class which PrintWriter
extends. Throwable.printStackTrace
takes a PrintWriter
because it calls the println
method on it which is not available in the Writer
class.println
is called because it needs to print the stack trace, one stack frame per line.
Andere Tipps
There could be a couple of reason
- The original implementation was to use PrintStream and the improved version of that is PrintWriter.
- The method prints lines of text and while it could create a PrintWriter on demand this is not ideal.
What they could have done is accept a Appendable which is the parent of Writer like this.
public void printStackTrace(Appendable appendable) {
PrintWriter pw = (appendable instanceof PrintWriter) ? (PrintWriter) appendable :
(appendable instanceof Writer) ? new PrintWriter((Writer) appendable) :
new printWriter(new AppendableWriter(appendable));
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow