diff --git a/java/core/src/main/java/com/google/protobuf/ProtobufToStringOutput.java b/java/core/src/main/java/com/google/protobuf/ProtobufToStringOutput.java index e6df9267d7884..f3deb3e8e64e1 100644 --- a/java/core/src/main/java/com/google/protobuf/ProtobufToStringOutput.java +++ b/java/core/src/main/java/com/google/protobuf/ProtobufToStringOutput.java @@ -1,10 +1,12 @@ package com.google.protobuf; +import java.util.Optional; + /** - * ProtobufToStringOutput controls the output format of {@link Message#toString()}. Specifically, for - * the Runnable object passed to `callWithDebugFormat` and `callWithTextFormat`, Message.toString() - * will always output the specified format unless ProtobufToStringOutput is used again to change the - * output format. + * ProtobufToStringOutput controls the output format of {@link Message#toString()}. Specifically, + * for the Runnable object passed to `callWithDebugFormat` and `callWithTextFormat`, + * Message.toString() will always output the specified format unless ProtobufToStringOutput is used + * again to change the output format. */ public final class ProtobufToStringOutput { private enum OutputMode { @@ -13,12 +15,14 @@ private enum OutputMode { } private static final ThreadLocal outputMode = - new ThreadLocal() { - @Override - protected OutputMode initialValue() { - return OutputMode.TEXT_FORMAT; - } - }; + ThreadLocal.withInitial(() -> OutputMode.TEXT_FORMAT); + + // Many tests are bound to the traditional Message.toString() output format (the text format). To + // accelerate the debug format adoption while avoiding breaking such tests, we introduce this + // test-only flag to disable the debug format in tests for certain libraries in which the output + // of Message.toString() is unlikely to be deserialized. + private static final ThreadLocal disableDebugFormatForTests = + ThreadLocal.withInitial(() -> false); private ProtobufToStringOutput() {} @@ -49,4 +53,8 @@ public static void callWithTextFormat(Runnable impl) { public static boolean shouldOutputDebugFormat() { return outputMode.get() == OutputMode.DEBUG_FORMAT; } + + static void setDisableDebugFormatForTests(boolean disable) { + disableDebugFormatForTests.set(disable); + } }