Add `@CanIgnoreReturnValue` as appropriate to Gson methods. (#2369)

This annotation indicates that return value of the annotated method does
not need to be used. If it is _not_ present on a non-void method, and if
Error Prone's `CheckReturnValue` is active, then calling the method
without using the result is an error. However, we are not enabling
`CheckReturnValue` by default here.

Also update some code that does ignore return values, so that the
returned value is used, if only by assigning it to an unused variable.
This commit is contained in:
Éamonn McManus 2023-04-10 10:50:25 -07:00 committed by GitHub
parent b43ccee889
commit c1da2d7070
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
32 changed files with 257 additions and 164 deletions

View File

@ -16,6 +16,7 @@
package com.google.gson.typeadapters;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
@ -179,6 +180,7 @@ public final class RuntimeTypeAdapterFactory<T> implements TypeAdapterFactory {
* Ensures that this factory will handle not just the given {@code baseType}, but any subtype
* of that type.
*/
@CanIgnoreReturnValue
public RuntimeTypeAdapterFactory<T> recognizeSubtypes() {
this.recognizeSubtypes = true;
return this;
@ -191,6 +193,7 @@ public final class RuntimeTypeAdapterFactory<T> implements TypeAdapterFactory {
* @throws IllegalArgumentException if either {@code type} or {@code label}
* have already been registered on this type adapter.
*/
@CanIgnoreReturnValue
public RuntimeTypeAdapterFactory<T> registerSubtype(Class<? extends T> type, String label) {
if (type == null || label == null) {
throw new NullPointerException();
@ -210,6 +213,7 @@ public final class RuntimeTypeAdapterFactory<T> implements TypeAdapterFactory {
* @throws IllegalArgumentException if either {@code type} or its simple name
* have already been registered on this type adapter.
*/
@CanIgnoreReturnValue
public RuntimeTypeAdapterFactory<T> registerSubtype(Class<? extends T> type) {
return registerSubtype(type, type.getSimpleName());
}

View File

@ -129,8 +129,8 @@ public final class GraphAdapterBuilderTest {
@Test
public void testSerializationWithMultipleTypes() {
Company google = new Company("Google");
new Employee("Jesse", google);
new Employee("Joel", google);
Employee unused1 = new Employee("Jesse", google);
Employee unused2 = new Employee("Joel", google);
GsonBuilder gsonBuilder = new GsonBuilder();
new GraphAdapterBuilder()

View File

@ -110,9 +110,9 @@ public final class InterceptorTest {
@Override public User read(JsonReader in) throws IOException {
in.beginObject();
in.nextName();
String unused1 = in.nextName();
String name = in.nextString();
in.nextName();
String unused2 = in.nextName();
String password = in.nextString();
in.endObject();
return new User(name, password);

View File

@ -64,7 +64,7 @@ public final class UtcDateTypeAdapterTest {
Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new UtcDateTypeAdapter())
.create();
gson.fromJson("'2014-12-05T04:00:00.000Z'", Date.class);
Date unused = gson.fromJson("'2014-12-05T04:00:00.000Z'", Date.class);
}
@Test

View File

@ -1223,7 +1223,7 @@ public final class Gson {
boolean oldLenient = reader.isLenient();
reader.setLenient(true);
try {
reader.peek();
JsonToken unused = reader.peek();
isEmpty = false;
TypeAdapter<T> typeAdapter = getAdapter(typeOfT);
return typeAdapter.read(reader);

View File

@ -28,6 +28,7 @@ import static com.google.gson.Gson.DEFAULT_SERIALIZE_NULLS;
import static com.google.gson.Gson.DEFAULT_SPECIALIZE_FLOAT_VALUES;
import static com.google.gson.Gson.DEFAULT_USE_JDK_UNSAFE;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.gson.annotations.Since;
import com.google.gson.annotations.Until;
import com.google.gson.internal.$Gson$Preconditions;
@ -159,6 +160,7 @@ public final class GsonBuilder {
* @see Since
* @see Until
*/
@CanIgnoreReturnValue
public GsonBuilder setVersion(double version) {
if (Double.isNaN(version) || version < 0.0) {
throw new IllegalArgumentException("Invalid version: " + version);
@ -181,6 +183,7 @@ public final class GsonBuilder {
* {@link java.lang.reflect.Modifier#STATIC}.
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
*/
@CanIgnoreReturnValue
public GsonBuilder excludeFieldsWithModifiers(int... modifiers) {
Objects.requireNonNull(modifiers);
excluder = excluder.withModifiers(modifiers);
@ -196,6 +199,7 @@ public final class GsonBuilder {
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
* @since 1.3
*/
@CanIgnoreReturnValue
public GsonBuilder generateNonExecutableJson() {
this.generateNonExecutableJson = true;
return this;
@ -210,6 +214,7 @@ public final class GsonBuilder {
*
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
*/
@CanIgnoreReturnValue
public GsonBuilder excludeFieldsWithoutExposeAnnotation() {
excluder = excluder.excludeFieldsWithoutExposeAnnotation();
return this;
@ -222,6 +227,7 @@ public final class GsonBuilder {
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
* @since 1.2
*/
@CanIgnoreReturnValue
public GsonBuilder serializeNulls() {
this.serializeNulls = true;
return this;
@ -306,6 +312,7 @@ public final class GsonBuilder {
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
* @since 1.7
*/
@CanIgnoreReturnValue
public GsonBuilder enableComplexMapKeySerialization() {
complexMapKeySerialization = true;
return this;
@ -330,6 +337,7 @@ public final class GsonBuilder {
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
* @since 1.3
*/
@CanIgnoreReturnValue
public GsonBuilder disableInnerClassSerialization() {
excluder = excluder.disableInnerClassSerialization();
return this;
@ -343,6 +351,7 @@ public final class GsonBuilder {
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
* @since 1.3
*/
@CanIgnoreReturnValue
public GsonBuilder setLongSerializationPolicy(LongSerializationPolicy serializationPolicy) {
this.longSerializationPolicy = Objects.requireNonNull(serializationPolicy);
return this;
@ -354,6 +363,7 @@ public final class GsonBuilder {
*
* <p>This method just delegates to {@link #setFieldNamingStrategy(FieldNamingStrategy)}.
*/
@CanIgnoreReturnValue
public GsonBuilder setFieldNamingPolicy(FieldNamingPolicy namingConvention) {
return setFieldNamingStrategy(namingConvention);
}
@ -370,6 +380,7 @@ public final class GsonBuilder {
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
* @since 1.3
*/
@CanIgnoreReturnValue
public GsonBuilder setFieldNamingStrategy(FieldNamingStrategy fieldNamingStrategy) {
this.fieldNamingPolicy = Objects.requireNonNull(fieldNamingStrategy);
return this;
@ -383,6 +394,7 @@ public final class GsonBuilder {
* @see ToNumberPolicy#DOUBLE The default object-to-number strategy
* @since 2.8.9
*/
@CanIgnoreReturnValue
public GsonBuilder setObjectToNumberStrategy(ToNumberStrategy objectToNumberStrategy) {
this.objectToNumberStrategy = Objects.requireNonNull(objectToNumberStrategy);
return this;
@ -396,6 +408,7 @@ public final class GsonBuilder {
* @see ToNumberPolicy#LAZILY_PARSED_NUMBER The default number-to-number strategy
* @since 2.8.9
*/
@CanIgnoreReturnValue
public GsonBuilder setNumberToNumberStrategy(ToNumberStrategy numberToNumberStrategy) {
this.numberToNumberStrategy = Objects.requireNonNull(numberToNumberStrategy);
return this;
@ -427,6 +440,7 @@ public final class GsonBuilder {
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
* @since 1.4
*/
@CanIgnoreReturnValue
public GsonBuilder setExclusionStrategies(ExclusionStrategy... strategies) {
Objects.requireNonNull(strategies);
for (ExclusionStrategy strategy : strategies) {
@ -450,6 +464,7 @@ public final class GsonBuilder {
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
* @since 1.7
*/
@CanIgnoreReturnValue
public GsonBuilder addSerializationExclusionStrategy(ExclusionStrategy strategy) {
Objects.requireNonNull(strategy);
excluder = excluder.withExclusionStrategy(strategy, true, false);
@ -471,6 +486,7 @@ public final class GsonBuilder {
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
* @since 1.7
*/
@CanIgnoreReturnValue
public GsonBuilder addDeserializationExclusionStrategy(ExclusionStrategy strategy) {
Objects.requireNonNull(strategy);
excluder = excluder.withExclusionStrategy(strategy, false, true);
@ -486,6 +502,7 @@ public final class GsonBuilder {
*
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
*/
@CanIgnoreReturnValue
public GsonBuilder setPrettyPrinting() {
return setPrettyPrinting(FormattingStyle.DEFAULT);
}
@ -500,6 +517,7 @@ public final class GsonBuilder {
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
* @since $next-version$
*/
@CanIgnoreReturnValue
public GsonBuilder setPrettyPrinting(FormattingStyle formattingStyle) {
this.formattingStyle = formattingStyle;
return this;
@ -515,6 +533,7 @@ public final class GsonBuilder {
* @see JsonReader#setLenient(boolean)
* @see JsonWriter#setLenient(boolean)
*/
@CanIgnoreReturnValue
public GsonBuilder setLenient() {
lenient = true;
return this;
@ -527,6 +546,7 @@ public final class GsonBuilder {
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
* @since 1.3
*/
@CanIgnoreReturnValue
public GsonBuilder disableHtmlEscaping() {
this.escapeHtmlChars = false;
return this;
@ -548,6 +568,7 @@ public final class GsonBuilder {
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
* @since 1.2
*/
@CanIgnoreReturnValue
public GsonBuilder setDateFormat(String pattern) {
// TODO(Joel): Make this fail fast if it is an invalid date format
this.datePattern = pattern;
@ -568,6 +589,7 @@ public final class GsonBuilder {
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
* @since 1.2
*/
@CanIgnoreReturnValue
public GsonBuilder setDateFormat(int style) {
this.dateStyle = style;
this.datePattern = null;
@ -589,6 +611,7 @@ public final class GsonBuilder {
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
* @since 1.2
*/
@CanIgnoreReturnValue
public GsonBuilder setDateFormat(int dateStyle, int timeStyle) {
this.dateStyle = dateStyle;
this.timeStyle = timeStyle;
@ -618,6 +641,7 @@ public final class GsonBuilder {
* {@link InstanceCreator}, {@link JsonSerializer}, and a {@link JsonDeserializer} interfaces.
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
*/
@CanIgnoreReturnValue
public GsonBuilder registerTypeAdapter(Type type, Object typeAdapter) {
Objects.requireNonNull(type);
$Gson$Preconditions.checkArgument(typeAdapter instanceof JsonSerializer<?>
@ -651,6 +675,7 @@ public final class GsonBuilder {
*
* @since 2.1
*/
@CanIgnoreReturnValue
public GsonBuilder registerTypeAdapterFactory(TypeAdapterFactory factory) {
Objects.requireNonNull(factory);
factories.add(factory);
@ -671,6 +696,7 @@ public final class GsonBuilder {
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
* @since 1.7
*/
@CanIgnoreReturnValue
public GsonBuilder registerTypeHierarchyAdapter(Class<?> baseType, Object typeAdapter) {
Objects.requireNonNull(baseType);
$Gson$Preconditions.checkArgument(typeAdapter instanceof JsonSerializer<?>
@ -707,6 +733,7 @@ public final class GsonBuilder {
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
* @since 1.3
*/
@CanIgnoreReturnValue
public GsonBuilder serializeSpecialFloatingPointValues() {
this.serializeSpecialFloatingPointValues = true;
return this;
@ -728,6 +755,7 @@ public final class GsonBuilder {
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
* @since 2.9.0
*/
@CanIgnoreReturnValue
public GsonBuilder disableJdkUnsafe() {
this.useJdkUnsafe = false;
return this;
@ -753,6 +781,7 @@ public final class GsonBuilder {
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
* @since 2.9.1
*/
@CanIgnoreReturnValue
public GsonBuilder addReflectionAccessFilter(ReflectionAccessFilter filter) {
Objects.requireNonNull(filter);
reflectionFilters.addFirst(filter);

View File

@ -16,6 +16,7 @@
package com.google.gson;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.gson.internal.NonNullElementWrapperList;
import java.math.BigDecimal;
import java.math.BigInteger;
@ -145,6 +146,7 @@ public final class JsonArray extends JsonElement implements Iterable<JsonElement
* @return the element previously at the specified position
* @throws IndexOutOfBoundsException if the specified index is outside the array bounds
*/
@CanIgnoreReturnValue
public JsonElement set(int index, JsonElement element) {
return elements.set(index, element == null ? JsonNull.INSTANCE : element);
}
@ -157,6 +159,7 @@ public final class JsonArray extends JsonElement implements Iterable<JsonElement
* @return true if this array contained the specified element, false otherwise
* @since 2.3
*/
@CanIgnoreReturnValue
public boolean remove(JsonElement element) {
return elements.remove(element);
}
@ -171,6 +174,7 @@ public final class JsonArray extends JsonElement implements Iterable<JsonElement
* @throws IndexOutOfBoundsException if the specified index is outside the array bounds
* @since 2.3
*/
@CanIgnoreReturnValue
public JsonElement remove(int index) {
return elements.remove(index);
}

View File

@ -16,6 +16,7 @@
package com.google.gson;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.gson.internal.Streams;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
@ -143,6 +144,7 @@ public abstract class JsonElement {
* @throws IllegalStateException if this element is of another type.
* @since 1.2
*/
@CanIgnoreReturnValue
public JsonNull getAsJsonNull() {
if (isJsonNull()) {
return (JsonNull) this;

View File

@ -16,6 +16,7 @@
package com.google.gson;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.gson.internal.LinkedTreeMap;
import java.util.Map;
import java.util.Set;
@ -77,6 +78,7 @@ public final class JsonObject extends JsonElement {
* member with this name exists.
* @since 1.3
*/
@CanIgnoreReturnValue
public JsonElement remove(String property) {
return members.remove(property);
}

View File

@ -15,6 +15,7 @@
*/
package com.google.gson;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.gson.internal.Streams;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
@ -33,7 +34,7 @@ import java.util.NoSuchElementException;
* <p>This class is conditionally thread-safe (see Item 70, Effective Java second edition). To
* properly use this class across multiple threads, you will need to add some external
* synchronization. For example:
*
*
* <pre>
* JsonStreamParser parser = new JsonStreamParser("['first'] {'second':10} 'third'");
* JsonElement element;

View File

@ -17,6 +17,7 @@
package com.google.gson.internal;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
@ -107,6 +108,7 @@ public final class LinkedTreeMap<K, V> extends AbstractMap<K, V> implements Seri
return findByObject(key) != null;
}
@CanIgnoreReturnValue
@Override public V put(K key, V value) {
if (key == null) {
throw new NullPointerException("key == null");

View File

@ -23,6 +23,7 @@ import com.google.gson.JsonParseException;
import com.google.gson.JsonSyntaxException;
import com.google.gson.internal.bind.TypeAdapters;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import com.google.gson.stream.MalformedJsonException;
import java.io.EOFException;
@ -44,7 +45,7 @@ public final class Streams {
public static JsonElement parse(JsonReader reader) throws JsonParseException {
boolean isEmpty = true;
try {
reader.peek();
JsonToken unused = reader.peek();
isEmpty = false;
return TypeAdapters.JSON_ELEMENT.read(reader);
} catch (EOFException e) {

View File

@ -16,6 +16,7 @@
package com.google.gson.internal.bind;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
@ -153,6 +154,7 @@ public final class JsonTreeReader extends JsonReader {
return stack[stackSize - 1];
}
@CanIgnoreReturnValue
private Object popStack() {
Object result = stack[--stackSize];
stack[stackSize] = null;

View File

@ -16,6 +16,7 @@
package com.google.gson.internal.bind;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
@ -92,6 +93,7 @@ public final class JsonTreeWriter extends JsonWriter {
}
}
@CanIgnoreReturnValue
@Override public JsonWriter beginArray() throws IOException {
JsonArray array = new JsonArray();
put(array);
@ -99,6 +101,7 @@ public final class JsonTreeWriter extends JsonWriter {
return this;
}
@CanIgnoreReturnValue
@Override public JsonWriter endArray() throws IOException {
if (stack.isEmpty() || pendingName != null) {
throw new IllegalStateException();
@ -111,6 +114,7 @@ public final class JsonTreeWriter extends JsonWriter {
throw new IllegalStateException();
}
@CanIgnoreReturnValue
@Override public JsonWriter beginObject() throws IOException {
JsonObject object = new JsonObject();
put(object);
@ -118,6 +122,7 @@ public final class JsonTreeWriter extends JsonWriter {
return this;
}
@CanIgnoreReturnValue
@Override public JsonWriter endObject() throws IOException {
if (stack.isEmpty() || pendingName != null) {
throw new IllegalStateException();
@ -130,6 +135,7 @@ public final class JsonTreeWriter extends JsonWriter {
throw new IllegalStateException();
}
@CanIgnoreReturnValue
@Override public JsonWriter name(String name) throws IOException {
Objects.requireNonNull(name, "name == null");
if (stack.isEmpty() || pendingName != null) {
@ -143,6 +149,7 @@ public final class JsonTreeWriter extends JsonWriter {
throw new IllegalStateException();
}
@CanIgnoreReturnValue
@Override public JsonWriter value(String value) throws IOException {
if (value == null) {
return nullValue();
@ -155,16 +162,19 @@ public final class JsonTreeWriter extends JsonWriter {
throw new UnsupportedOperationException();
}
@CanIgnoreReturnValue
@Override public JsonWriter nullValue() throws IOException {
put(JsonNull.INSTANCE);
return this;
}
@CanIgnoreReturnValue
@Override public JsonWriter value(boolean value) throws IOException {
put(new JsonPrimitive(value));
return this;
}
@CanIgnoreReturnValue
@Override public JsonWriter value(Boolean value) throws IOException {
if (value == null) {
return nullValue();
@ -173,6 +183,7 @@ public final class JsonTreeWriter extends JsonWriter {
return this;
}
@CanIgnoreReturnValue
@Override public JsonWriter value(float value) throws IOException {
if (!isLenient() && (Float.isNaN(value) || Float.isInfinite(value))) {
throw new IllegalArgumentException("JSON forbids NaN and infinities: " + value);
@ -181,6 +192,7 @@ public final class JsonTreeWriter extends JsonWriter {
return this;
}
@CanIgnoreReturnValue
@Override public JsonWriter value(double value) throws IOException {
if (!isLenient() && (Double.isNaN(value) || Double.isInfinite(value))) {
throw new IllegalArgumentException("JSON forbids NaN and infinities: " + value);
@ -189,11 +201,13 @@ public final class JsonTreeWriter extends JsonWriter {
return this;
}
@CanIgnoreReturnValue
@Override public JsonWriter value(long value) throws IOException {
put(new JsonPrimitive(value));
return this;
}
@CanIgnoreReturnValue
@Override public JsonWriter value(Number value) throws IOException {
if (value == null) {
return nullValue();

View File

@ -1119,7 +1119,7 @@ public class JsonReader implements Closeable {
return;
} else if (c == '\\') {
pos = p;
readEscapeCharacter();
char unused = readEscapeCharacter();
p = pos;
l = limit;
} else if (c == '\n') {
@ -1664,7 +1664,7 @@ public class JsonReader implements Closeable {
*/
private void consumeNonExecutePrefix() throws IOException {
// fast forward through the leading whitespace
nextNonWhitespace(true);
int unused = nextNonWhitespace(true);
pos--;
if (pos + 5 > limit && !fillBuffer(5)) {

View File

@ -24,6 +24,7 @@ import static com.google.gson.stream.JsonScope.NONEMPTY_ARRAY;
import static com.google.gson.stream.JsonScope.NONEMPTY_DOCUMENT;
import static com.google.gson.stream.JsonScope.NONEMPTY_OBJECT;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.Closeable;
import java.io.Flushable;
import java.io.IOException;
@ -318,6 +319,7 @@ public class JsonWriter implements Closeable, Flushable {
*
* @return this writer.
*/
@CanIgnoreReturnValue
public JsonWriter beginArray() throws IOException {
writeDeferredName();
return open(EMPTY_ARRAY, '[');
@ -328,6 +330,7 @@ public class JsonWriter implements Closeable, Flushable {
*
* @return this writer.
*/
@CanIgnoreReturnValue
public JsonWriter endArray() throws IOException {
return close(EMPTY_ARRAY, NONEMPTY_ARRAY, ']');
}
@ -338,6 +341,7 @@ public class JsonWriter implements Closeable, Flushable {
*
* @return this writer.
*/
@CanIgnoreReturnValue
public JsonWriter beginObject() throws IOException {
writeDeferredName();
return open(EMPTY_OBJECT, '{');
@ -348,6 +352,7 @@ public class JsonWriter implements Closeable, Flushable {
*
* @return this writer.
*/
@CanIgnoreReturnValue
public JsonWriter endObject() throws IOException {
return close(EMPTY_OBJECT, NONEMPTY_OBJECT, '}');
}
@ -356,6 +361,7 @@ public class JsonWriter implements Closeable, Flushable {
* Enters a new scope by appending any necessary whitespace and the given
* bracket.
*/
@CanIgnoreReturnValue
private JsonWriter open(int empty, char openBracket) throws IOException {
beforeValue();
push(empty);
@ -367,6 +373,7 @@ public class JsonWriter implements Closeable, Flushable {
* Closes the current scope by appending any necessary whitespace and the
* given bracket.
*/
@CanIgnoreReturnValue
private JsonWriter close(int empty, int nonempty, char closeBracket)
throws IOException {
int context = peek();
@ -415,6 +422,7 @@ public class JsonWriter implements Closeable, Flushable {
* @param name the name of the forthcoming value. May not be null.
* @return this writer.
*/
@CanIgnoreReturnValue
public JsonWriter name(String name) throws IOException {
Objects.requireNonNull(name, "name == null");
if (deferredName != null) {
@ -441,6 +449,7 @@ public class JsonWriter implements Closeable, Flushable {
* @param value the literal string value, or null to encode a null literal.
* @return this writer.
*/
@CanIgnoreReturnValue
public JsonWriter value(String value) throws IOException {
if (value == null) {
return nullValue();
@ -462,6 +471,7 @@ public class JsonWriter implements Closeable, Flushable {
* writing raw JSON values.
* @since 2.4
*/
@CanIgnoreReturnValue
public JsonWriter jsonValue(String value) throws IOException {
if (value == null) {
return nullValue();
@ -477,6 +487,7 @@ public class JsonWriter implements Closeable, Flushable {
*
* @return this writer.
*/
@CanIgnoreReturnValue
public JsonWriter nullValue() throws IOException {
if (deferredName != null) {
if (serializeNulls) {
@ -496,6 +507,7 @@ public class JsonWriter implements Closeable, Flushable {
*
* @return this writer.
*/
@CanIgnoreReturnValue
public JsonWriter value(boolean value) throws IOException {
writeDeferredName();
beforeValue();
@ -509,6 +521,7 @@ public class JsonWriter implements Closeable, Flushable {
* @return this writer.
* @since 2.7
*/
@CanIgnoreReturnValue
public JsonWriter value(Boolean value) throws IOException {
if (value == null) {
return nullValue();
@ -530,6 +543,7 @@ public class JsonWriter implements Closeable, Flushable {
* #setLenient(boolean) lenient}.
* @since 2.9.1
*/
@CanIgnoreReturnValue
public JsonWriter value(float value) throws IOException {
writeDeferredName();
if (!lenient && (Float.isNaN(value) || Float.isInfinite(value))) {
@ -549,6 +563,7 @@ public class JsonWriter implements Closeable, Flushable {
* @throws IllegalArgumentException if the value is NaN or Infinity and this writer is
* not {@link #setLenient(boolean) lenient}.
*/
@CanIgnoreReturnValue
public JsonWriter value(double value) throws IOException {
writeDeferredName();
if (!lenient && (Double.isNaN(value) || Double.isInfinite(value))) {
@ -564,6 +579,7 @@ public class JsonWriter implements Closeable, Flushable {
*
* @return this writer.
*/
@CanIgnoreReturnValue
public JsonWriter value(long value) throws IOException {
writeDeferredName();
beforeValue();
@ -593,6 +609,7 @@ public class JsonWriter implements Closeable, Flushable {
* not {@link #setLenient(boolean) lenient}; or if the {@code toString()} result is not a
* valid JSON number.
*/
@CanIgnoreReturnValue
public JsonWriter value(Number value) throws IOException {
if (value == null) {
return nullValue();

View File

@ -70,8 +70,8 @@ public class JsonStreamParserTest {
@Test
public void testCallingNextBeyondAvailableInput() {
parser.next();
parser.next();
JsonElement unused1 = parser.next();
JsonElement unused2 = parser.next();
try {
parser.next();
fail("Parser should not go beyond available input");

View File

@ -88,11 +88,11 @@ public final class MixedStreamTest {
jsonReader.beginArray();
jsonReader.setLenient(false);
gson.fromJson(jsonReader, Car.class);
Car unused1 = gson.fromJson(jsonReader, Car.class);
assertThat(jsonReader.isLenient()).isFalse();
jsonReader.setLenient(true);
gson.fromJson(jsonReader, Car.class);
Car unused2 = gson.fromJson(jsonReader, Car.class);
assertThat(jsonReader.isLenient()).isTrue();
}

View File

@ -27,7 +27,7 @@ import org.junit.Test;
/**
* Tests for ensuring Gson thread-safety.
*
*
* @author Inderjeet Singh
* @author Joel Leitch
*/
@ -44,23 +44,23 @@ public class ConcurrencyTest {
* http://groups.google.com/group/google-gson/browse_thread/thread/563bb51ee2495081
*/
@Test
public void testSingleThreadSerialization() {
MyObject myObj = new MyObject();
for (int i = 0; i < 10; i++) {
gson.toJson(myObj);
}
}
public void testSingleThreadSerialization() {
MyObject myObj = new MyObject();
for (int i = 0; i < 10; i++) {
String unused = gson.toJson(myObj);
}
}
/**
* Source-code based on
* http://groups.google.com/group/google-gson/browse_thread/thread/563bb51ee2495081
*/
@Test
public void testSingleThreadDeserialization() {
for (int i = 0; i < 10; i++) {
gson.fromJson("{'a':'hello','b':'world','i':1}", MyObject.class);
}
}
public void testSingleThreadDeserialization() {
for (int i = 0; i < 10; i++) {
MyObject unused = gson.fromJson("{'a':'hello','b':'world','i':1}", MyObject.class);
}
}
/**
* Source-code based on
@ -79,7 +79,7 @@ public class ConcurrencyTest {
try {
startLatch.await();
for (int i = 0; i < 10; i++) {
gson.toJson(myObj);
String unused = gson.toJson(myObj);
}
} catch (Throwable t) {
failed.set(true);
@ -110,7 +110,7 @@ public class ConcurrencyTest {
try {
startLatch.await();
for (int i = 0; i < 10; i++) {
gson.fromJson("{'a':'hello','b':'world','i':1}", MyObject.class);
MyObject unused = gson.fromJson("{'a':'hello','b':'world','i':1}", MyObject.class);
}
} catch (Throwable t) {
failed.set(true);
@ -124,7 +124,7 @@ public class ConcurrencyTest {
finishedLatch.await();
assertThat(failed.get()).isFalse();
}
@SuppressWarnings("unused")
private static class MyObject {
String a;

View File

@ -127,7 +127,7 @@ public class DefaultTypeAdaptersTest {
URL target = gson.fromJson(json, URL.class);
assertThat(target.toExternalForm()).isEqualTo(urlValue);
gson.fromJson('"' + urlValue + '"', URL.class);
URL unused = gson.fromJson('"' + urlValue + '"', URL.class);
assertThat(target.toExternalForm()).isEqualTo(urlValue);
}

View File

@ -17,6 +17,7 @@ package com.google.gson.functional;
import static com.google.common.truth.Truth.assertThat;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
@ -40,7 +41,7 @@ import org.junit.Before;
import org.junit.Test;
/**
* Functional tests for Json serialization and deserialization of classes with
* Functional tests for Json serialization and deserialization of classes with
* inheritance hierarchies.
*
* @author Inderjeet Singh
@ -85,7 +86,7 @@ public class InheritanceTest {
ClassWithBaseArrayField sub = new ClassWithBaseArrayField(baseClasses);
JsonObject json = gson.toJsonTree(sub).getAsJsonObject();
JsonArray bases = json.get(ClassWithBaseArrayField.FIELD_KEY).getAsJsonArray();
for (JsonElement element : bases) {
for (JsonElement element : bases) {
assertThat(element.getAsJsonObject().get(Sub.SUB_FIELD_KEY).getAsString()).isEqualTo(Sub.SUB_NAME);
}
}
@ -98,7 +99,7 @@ public class InheritanceTest {
ClassWithBaseCollectionField sub = new ClassWithBaseCollectionField(baseClasses);
JsonObject json = gson.toJsonTree(sub).getAsJsonObject();
JsonArray bases = json.get(ClassWithBaseArrayField.FIELD_KEY).getAsJsonArray();
for (JsonElement element : bases) {
for (JsonElement element : bases) {
assertThat(element.getAsJsonObject().get(Sub.SUB_FIELD_KEY).getAsString()).isEqualTo(Sub.SUB_NAME);
}
}
@ -194,14 +195,14 @@ public class InheritanceTest {
String json = "{\"list\":[0,1,2,3],\"queue\":[0,1,2,3],\"set\":[0.1,0.2,0.3,0.4],"
+ "\"sortedSet\":[\"a\",\"b\",\"c\",\"d\"]"
+ "}";
ClassWithSubInterfacesOfCollection target =
ClassWithSubInterfacesOfCollection target =
gson.fromJson(json, ClassWithSubInterfacesOfCollection.class);
assertThat(target.listContains(0, 1, 2, 3)).isTrue();
assertThat(target.queueContains(0, 1, 2, 3)).isTrue();
assertThat(target.setContains(0.1F, 0.2F, 0.3F, 0.4F)).isTrue();
assertThat(target.sortedSetContains('a', 'b', 'c', 'd')).isTrue();
}
private static class ClassWithSubInterfacesOfCollection {
private List<Integer> list;
private Queue<Long> queue;
@ -224,7 +225,7 @@ public class InheritanceTest {
}
return true;
}
boolean queueContains(long... values) {
for (long value : values) {
if (!queue.contains(value)) {
@ -233,7 +234,7 @@ public class InheritanceTest {
}
return true;
}
boolean setContains(float... values) {
for (float value : values) {
if (!set.contains(value)) {
@ -251,7 +252,7 @@ public class InheritanceTest {
}
return true;
}
public String getExpectedJson() {
StringBuilder sb = new StringBuilder();
sb.append("{");
@ -267,6 +268,7 @@ public class InheritanceTest {
return sb.toString();
}
@CanIgnoreReturnValue
private StringBuilder append(StringBuilder sb, Collection<?> c) {
sb.append("[");
boolean first = true;

View File

@ -118,7 +118,7 @@ public final class JsonAdapterAnnotationOnFieldsTest {
out.value("PartJsonFieldAnnotationAdapter");
}
@Override public Part read(JsonReader in) throws IOException {
in.nextString();
String unused = in.nextString();
return new Part("PartJsonFieldAnnotationAdapter");
}
}
@ -131,7 +131,7 @@ public final class JsonAdapterAnnotationOnFieldsTest {
}
@SuppressWarnings("unchecked")
@Override public T read(JsonReader in) throws IOException {
in.nextString();
String unused = in.nextString();
return (T) new Part("GizmoPartTypeAdapterFactory");
}
};
@ -158,7 +158,7 @@ public final class JsonAdapterAnnotationOnFieldsTest {
out.value("UserClassAnnotationAdapter");
}
@Override public User read(JsonReader in) throws IOException {
in.nextString();
String unused = in.nextString();
return new User("UserClassAnnotationAdapter");
}
}
@ -177,7 +177,7 @@ public final class JsonAdapterAnnotationOnFieldsTest {
out.value("UserFieldAnnotationAdapter");
}
@Override public User read(JsonReader in) throws IOException {
in.nextString();
String unused = in.nextString();
return new User("UserFieldAnnotationAdapter");
}
}
@ -187,7 +187,7 @@ public final class JsonAdapterAnnotationOnFieldsTest {
out.value("RegisteredUserAdapter");
}
@Override public User read(JsonReader in) throws IOException {
in.nextString();
String unused = in.nextString();
return new User("RegisteredUserAdapter");
}
}
@ -307,7 +307,7 @@ public final class JsonAdapterAnnotationOnFieldsTest {
}
@SuppressWarnings("unchecked")
@Override public T read(JsonReader in) throws IOException {
in.nextString();
String unused = in.nextString();
return (T) Arrays.asList(new Part("GizmoPartTypeAdapterFactory"));
}
};

View File

@ -539,17 +539,17 @@ public class ObjectTest {
Gson gson = new Gson();
Product product = new Product();
assertThat(gson.toJson(product)).isEqualTo("{\"attributes\":[],\"departments\":[]}");
gson.fromJson(gson.toJson(product), Product.class);
Product unused1 = gson.fromJson(gson.toJson(product), Product.class);
product.departments.add(new Department());
assertThat(gson.toJson(product))
.isEqualTo("{\"attributes\":[],\"departments\":[{\"name\":\"abc\",\"code\":\"123\"}]}");
gson.fromJson(gson.toJson(product), Product.class);
Product unused2 = gson.fromJson(gson.toJson(product), Product.class);
product.attributes.add("456");
assertThat(gson.toJson(product))
.isEqualTo("{\"attributes\":[\"456\"],\"departments\":[{\"name\":\"abc\",\"code\":\"123\"}]}");
gson.fromJson(gson.toJson(product), Product.class);
Product unused3 = gson.fromJson(gson.toJson(product), Product.class);
}
static final class Department {
@ -611,7 +611,7 @@ public class ObjectTest {
@Test
public void testStaticFieldDeserialization() {
// By default Gson should ignore static fields
gson.fromJson("{\"s\":\"custom\"}", ClassWithStaticField.class);
ClassWithStaticField unused = gson.fromJson("{\"s\":\"custom\"}", ClassWithStaticField.class);
assertThat(ClassWithStaticField.s).isEqualTo("initial");
Gson gson = new GsonBuilder()

View File

@ -18,6 +18,7 @@ package com.google.gson.functional;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonStreamParser;
@ -155,12 +156,14 @@ public class ReadersWritersTest {
final StringBuilder stringBuilder = new StringBuilder();
int toStringCallCount = 0;
@CanIgnoreReturnValue
@Override
public Appendable append(char c) throws IOException {
stringBuilder.append(c);
return this;
}
@CanIgnoreReturnValue
@Override
public Appendable append(CharSequence csq) throws IOException {
if (csq == null) {
@ -170,6 +173,7 @@ public class ReadersWritersTest {
return this;
}
@CanIgnoreReturnValue
@Override
public Appendable append(CharSequence csq, int start, int end) throws IOException {
if (csq == null) {

View File

@ -17,6 +17,7 @@ package com.google.gson.functional;
import static com.google.common.truth.Truth.assertThat;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
@ -124,6 +125,7 @@ public final class RuntimeTypeAdapterFactoryFunctionalTest {
* @throws IllegalArgumentException if either {@code type} or {@code label}
* have already been registered on this type adapter.
*/
@CanIgnoreReturnValue
public RuntimeTypeAdapterFactory<T> registerSubtype(Class<? extends T> type, String label) {
if (type == null || label == null) {
throw new NullPointerException();
@ -143,6 +145,7 @@ public final class RuntimeTypeAdapterFactoryFunctionalTest {
* @throws IllegalArgumentException if either {@code type} or its simple name
* have already been registered on this type adapter.
*/
@CanIgnoreReturnValue
public RuntimeTypeAdapterFactory<T> registerSubtype(Class<? extends T> type) {
return registerSubtype(type, type.getSimpleName());
}

View File

@ -136,7 +136,7 @@ public final class TypeHierarchyAdapterTest {
/** This behaviour changed in Gson 2.1; it used to throw. */
@Test
public void testRegisterSubTypeFirstAllowed() {
new GsonBuilder()
Gson unused = new GsonBuilder()
.registerTypeHierarchyAdapter(Manager.class, new ManagerAdapter())
.registerTypeHierarchyAdapter(Employee.class, new EmployeeAdapter())
.create();

View File

@ -332,9 +332,9 @@ public final class JsonElementReaderTest {
fail();
} catch (IllegalStateException expected) {
}
reader.nextName();
String unused1 = reader.nextName();
assertThat(new JsonPrimitive(1)).isEqualTo(reader.nextJsonElement());
reader.nextName();
String unused2 = reader.nextName();
reader.beginObject();
try {
reader.nextJsonElement();
@ -342,7 +342,7 @@ public final class JsonElementReaderTest {
} catch (IllegalStateException expected) {
}
reader.endObject();
reader.nextName();
String unused3 = reader.nextName();
reader.beginArray();
try {
reader.nextJsonElement();

View File

@ -35,7 +35,7 @@ import org.junit.Test;
/**
* Tests to measure performance for Gson. All tests in this file will be disabled in code. To run
* them remove disabled_ prefix from the tests and run them.
*
*
* @author Inderjeet Singh
* @author Joel Leitch
*/
@ -50,7 +50,7 @@ public class PerformanceTest {
public void setUp() throws Exception {
gson = new Gson();
}
@Test
public void testDummy() {
// This is here to prevent Junit for complaining when we disable all tests.
@ -74,7 +74,7 @@ public class PerformanceTest {
}
}
}
private void parseLongJson(String json) throws JsonParseException {
ExceptionHolder target = gson.fromJson(json, ExceptionHolder.class);
assertThat(target.message).contains("Error");
@ -84,7 +84,7 @@ public class PerformanceTest {
private static class ExceptionHolder {
public final String message;
public final String stackTrace;
// For use by Gson
@SuppressWarnings("unused")
private ExceptionHolder() {
@ -111,7 +111,7 @@ public class PerformanceTest {
this.value = value;
}
}
/**
* Created in response to http://code.google.com/p/google-gson/issues/detail?id=96
*/
@ -122,10 +122,10 @@ public class PerformanceTest {
List<CollectionEntry> list = new ArrayList<>(count);
for (int i = 0; i < count; ++i) {
list.add(new CollectionEntry("name"+i,"value"+i));
}
gson.toJson(list);
}
String unused = gson.toJson(list);
}
/**
* Created in response to http://code.google.com/p/google-gson/issues/detail?id=96
*/
@ -143,7 +143,7 @@ public class PerformanceTest {
sb.append(',');
}
sb.append("{name:'name").append(i).append("',value:'value").append(i).append("'}");
}
}
sb.append(']');
String json = sb.toString();
Type collectionType = new TypeToken<ArrayList<CollectionEntry>>(){}.getType();
@ -163,11 +163,11 @@ public class PerformanceTest {
for (int i = 0; i < size; ++i) {
ba[i] = 0x05;
}
gson.toJson(ba);
String unused = gson.toJson(ba);
System.out.printf("Gson could serialize a byte array of size: %d\n", size);
}
}
/**
* Created in response to http://code.google.com/p/google-gson/issues/detail?id=96
*/
@ -197,7 +197,7 @@ public class PerformanceTest {
// The tests to measure serialization and deserialization performance of Gson
// Based on the discussion at
// http://groups.google.com/group/google-gson/browse_thread/thread/7a50b17a390dfaeb
// Test results: 10/19/2009
// Test results: 10/19/2009
// Serialize classes avg time: 60 ms
// Deserialized classes avg time: 70 ms
// Serialize exposed classes avg time: 159 ms
@ -206,16 +206,16 @@ public class PerformanceTest {
@Test
@Ignore
public void disabled_testSerializeClasses() {
ClassWithList c = new ClassWithList("str");
for (int i = 0; i < COLLECTION_SIZE; ++i) {
c.list.add(new ClassWithField("element-" + i));
ClassWithList c = new ClassWithList("str");
for (int i = 0; i < COLLECTION_SIZE; ++i) {
c.list.add(new ClassWithField("element-" + i));
}
StringWriter w = new StringWriter();
long t1 = System.currentTimeMillis();
for (int i = 0; i < NUM_ITERATIONS; ++i) {
gson.toJson(c, w);
}
long t2 = System.currentTimeMillis();
StringWriter w = new StringWriter();
long t1 = System.currentTimeMillis();
for (int i = 0; i < NUM_ITERATIONS; ++i) {
gson.toJson(c, w);
}
long t2 = System.currentTimeMillis();
long avg = (t2 - t1) / NUM_ITERATIONS;
System.out.printf("Serialize classes avg time: %d ms\n", avg);
}
@ -225,11 +225,11 @@ public class PerformanceTest {
public void disabled_testDeserializeClasses() {
String json = buildJsonForClassWithList();
ClassWithList[] target = new ClassWithList[NUM_ITERATIONS];
long t1 = System.currentTimeMillis();
long t1 = System.currentTimeMillis();
for (int i = 0; i < NUM_ITERATIONS; ++i) {
target[i] = gson.fromJson(json, ClassWithList.class);
}
long t2 = System.currentTimeMillis();
long t2 = System.currentTimeMillis();
long avg = (t2 - t1) / NUM_ITERATIONS;
System.out.printf("Deserialize classes avg time: %d ms\n", avg);
}
@ -241,33 +241,33 @@ public class PerformanceTest {
for (long l = 0; l < 100000; l++) {
largeObject.put("field" + l, l);
}
long t1 = System.currentTimeMillis();
long t1 = System.currentTimeMillis();
String json = gson.toJson(largeObject);
long t2 = System.currentTimeMillis();
System.out.printf("Large object serialized in: %d ms\n", (t2 - t1));
t1 = System.currentTimeMillis();
gson.fromJson(json, new TypeToken<Map<String, Long>>() {}.getType());
t1 = System.currentTimeMillis();
Map<String, Long> unused = gson.fromJson(json, new TypeToken<Map<String, Long>>() {}.getType());
t2 = System.currentTimeMillis();
System.out.printf("Large object deserialized in: %d ms\n", (t2 - t1));
}
@Test
@Ignore
public void disabled_testSerializeExposedClasses() {
ClassWithListOfObjects c1 = new ClassWithListOfObjects("str");
for (int i1 = 0; i1 < COLLECTION_SIZE; ++i1) {
c1.list.add(new ClassWithExposedField("element-" + i1));
ClassWithListOfObjects c1 = new ClassWithListOfObjects("str");
for (int i1 = 0; i1 < COLLECTION_SIZE; ++i1) {
c1.list.add(new ClassWithExposedField("element-" + i1));
}
ClassWithListOfObjects c = c1;
StringWriter w = new StringWriter();
long t1 = System.currentTimeMillis();
for (int i = 0; i < NUM_ITERATIONS; ++i) {
gson.toJson(c, w);
}
long t2 = System.currentTimeMillis();
ClassWithListOfObjects c = c1;
StringWriter w = new StringWriter();
long t1 = System.currentTimeMillis();
for (int i = 0; i < NUM_ITERATIONS; ++i) {
gson.toJson(c, w);
}
long t2 = System.currentTimeMillis();
long avg = (t2 - t1) / NUM_ITERATIONS;
System.out.printf("Serialize exposed classes avg time: %d ms\n", avg);
}
@ -277,11 +277,11 @@ public class PerformanceTest {
public void disabled_testDeserializeExposedClasses() {
String json = buildJsonForClassWithList();
ClassWithListOfObjects[] target = new ClassWithListOfObjects[NUM_ITERATIONS];
long t1 = System.currentTimeMillis();
long t1 = System.currentTimeMillis();
for (int i = 0; i < NUM_ITERATIONS; ++i) {
target[i] = gson.fromJson(json, ClassWithListOfObjects.class);
}
long t2 = System.currentTimeMillis();
long t2 = System.currentTimeMillis();
long avg = (t2 - t1) / NUM_ITERATIONS;
System.out.printf("Deserialize exposed classes avg time: %d ms\n", avg);
}
@ -297,7 +297,7 @@ public class PerformanceTest {
Gson gson = new Gson();
String json = gson.toJson(original);
Type longToLong = new TypeToken<Map<Long, Long>>(){}.getType();
gson.fromJson(json, longToLong);
Map<Long, Long> unused = gson.fromJson(json, longToLong);
}
private String buildJsonForClassWithList() {
@ -320,8 +320,8 @@ public class PerformanceTest {
}
@SuppressWarnings("unused")
private static final class ClassWithList {
final String field;
private static final class ClassWithList {
final String field;
final List<ClassWithField> list = new ArrayList<>(COLLECTION_SIZE);
ClassWithList() {
this(null);
@ -329,24 +329,24 @@ public class PerformanceTest {
ClassWithList(String field) {
this.field = field;
}
}
}
@SuppressWarnings("unused")
private static final class ClassWithField {
private static final class ClassWithField {
final String field;
ClassWithField() {
this("");
}
public ClassWithField(String field) {
this.field = field;
}
public ClassWithField(String field) {
this.field = field;
}
}
@SuppressWarnings("unused")
private static final class ClassWithListOfObjects {
@Expose
final String field;
@Expose
private static final class ClassWithListOfObjects {
@Expose
final String field;
@Expose
final List<ClassWithExposedField> list = new ArrayList<>(COLLECTION_SIZE);
ClassWithListOfObjects() {
this(null);
@ -354,17 +354,17 @@ public class PerformanceTest {
ClassWithListOfObjects(String field) {
this.field = field;
}
}
}
@SuppressWarnings("unused")
private static final class ClassWithExposedField {
@Expose
private static final class ClassWithExposedField {
@Expose
final String field;
ClassWithExposedField() {
this("");
}
ClassWithExposedField(String field) {
this.field = field;
}
ClassWithExposedField(String field) {
this.field = field;
}
}
}

View File

@ -30,7 +30,7 @@ public class JsonAdapterNullSafeTest {
@Test
public void testNullSafeBugSerialize() {
Device device = new Device("ec57803e");
gson.toJson(device);
String unused = gson.toJson(device);
}
@Test

View File

@ -51,34 +51,34 @@ public class JsonReaderPathTest {
reader.beginObject();
assertThat(reader.getPreviousPath()).isEqualTo("$.");
assertThat(reader.getPath()).isEqualTo("$.");
reader.nextName();
String unused1 = reader.nextName();
assertThat(reader.getPreviousPath()).isEqualTo("$.a");
assertThat(reader.getPath()).isEqualTo("$.a");
reader.beginArray();
assertThat(reader.getPreviousPath()).isEqualTo("$.a[0]");
assertThat(reader.getPath()).isEqualTo("$.a[0]");
reader.nextInt();
int unused2 = reader.nextInt();
assertThat(reader.getPreviousPath()).isEqualTo("$.a[0]");
assertThat(reader.getPath()).isEqualTo("$.a[1]");
reader.nextBoolean();
boolean unused3 = reader.nextBoolean();
assertThat(reader.getPreviousPath()).isEqualTo("$.a[1]");
assertThat(reader.getPath()).isEqualTo("$.a[2]");
reader.nextBoolean();
boolean unused4 = reader.nextBoolean();
assertThat(reader.getPreviousPath()).isEqualTo("$.a[2]");
assertThat(reader.getPath()).isEqualTo("$.a[3]");
reader.nextNull();
assertThat(reader.getPreviousPath()).isEqualTo("$.a[3]");
assertThat(reader.getPath()).isEqualTo("$.a[4]");
reader.nextString();
String unused5 = reader.nextString();
assertThat(reader.getPreviousPath()).isEqualTo("$.a[4]");
assertThat(reader.getPath()).isEqualTo("$.a[5]");
reader.beginObject();
assertThat(reader.getPreviousPath()).isEqualTo("$.a[5].");
assertThat(reader.getPath()).isEqualTo("$.a[5].");
reader.nextName();
String unused6 = reader.nextName();
assertThat(reader.getPreviousPath()).isEqualTo("$.a[5].c");
assertThat(reader.getPath()).isEqualTo("$.a[5].c");
reader.nextString();
String unused7 = reader.nextString();
assertThat(reader.getPreviousPath()).isEqualTo("$.a[5].c");
assertThat(reader.getPath()).isEqualTo("$.a[5].c");
reader.endObject();
@ -87,7 +87,7 @@ public class JsonReaderPathTest {
reader.beginArray();
assertThat(reader.getPreviousPath()).isEqualTo("$.a[6][0]");
assertThat(reader.getPath()).isEqualTo("$.a[6][0]");
reader.nextInt();
int unused8 = reader.nextInt();
assertThat(reader.getPreviousPath()).isEqualTo("$.a[6][0]");
assertThat(reader.getPath()).isEqualTo("$.a[6][1]");
reader.endArray();
@ -106,49 +106,49 @@ public class JsonReaderPathTest {
assertThat(reader.getPreviousPath()).isEqualTo("$");
assertThat(reader.getPath()).isEqualTo("$");
reader.peek();
JsonToken unused1 = reader.peek();
assertThat(reader.getPreviousPath()).isEqualTo("$");
assertThat(reader.getPath()).isEqualTo("$");
reader.beginObject();
assertThat(reader.getPreviousPath()).isEqualTo("$.");
assertThat(reader.getPath()).isEqualTo("$.");
reader.peek();
JsonToken unused2 = reader.peek();
assertThat(reader.getPreviousPath()).isEqualTo("$.");
assertThat(reader.getPath()).isEqualTo("$.");
reader.nextName();
String unused3 = reader.nextName();
assertThat(reader.getPreviousPath()).isEqualTo("$.a");
assertThat(reader.getPath()).isEqualTo("$.a");
reader.peek();
JsonToken unused4 = reader.peek();
assertThat(reader.getPreviousPath()).isEqualTo("$.a");
assertThat(reader.getPath()).isEqualTo("$.a");
reader.nextInt();
int unused5 = reader.nextInt();
assertThat(reader.getPreviousPath()).isEqualTo("$.a");
assertThat(reader.getPath()).isEqualTo("$.a");
reader.peek();
JsonToken unused6 = reader.peek();
assertThat(reader.getPreviousPath()).isEqualTo("$.a");
assertThat(reader.getPath()).isEqualTo("$.a");
reader.nextName();
String unused7 = reader.nextName();
assertThat(reader.getPreviousPath()).isEqualTo("$.b");
assertThat(reader.getPath()).isEqualTo("$.b");
reader.peek();
JsonToken unused8 = reader.peek();
assertThat(reader.getPreviousPath()).isEqualTo("$.b");
assertThat(reader.getPath()).isEqualTo("$.b");
reader.nextInt();
int unused9 = reader.nextInt();
assertThat(reader.getPreviousPath()).isEqualTo("$.b");
assertThat(reader.getPath()).isEqualTo("$.b");
reader.peek();
JsonToken unused10 = reader.peek();
assertThat(reader.getPreviousPath()).isEqualTo("$.b");
assertThat(reader.getPath()).isEqualTo("$.b");
reader.endObject();
assertThat(reader.getPreviousPath()).isEqualTo("$");
assertThat(reader.getPath()).isEqualTo("$");
reader.peek();
JsonToken unused11 = reader.peek();
assertThat(reader.getPreviousPath()).isEqualTo("$");
assertThat(reader.getPath()).isEqualTo("$");
reader.close();
@ -161,35 +161,35 @@ public class JsonReaderPathTest {
assertThat(reader.getPreviousPath()).isEqualTo("$");
assertThat(reader.getPath()).isEqualTo("$");
reader.peek();
JsonToken unused1 = reader.peek();
assertThat(reader.getPreviousPath()).isEqualTo("$");
assertThat(reader.getPath()).isEqualTo("$");
reader.beginArray();
assertThat(reader.getPreviousPath()).isEqualTo("$[0]");
assertThat(reader.getPath()).isEqualTo("$[0]");
reader.peek();
JsonToken unused2 = reader.peek();
assertThat(reader.getPreviousPath()).isEqualTo("$[0]");
assertThat(reader.getPath()).isEqualTo("$[0]");
reader.nextInt();
int unused3 = reader.nextInt();
assertThat(reader.getPreviousPath()).isEqualTo("$[0]");
assertThat(reader.getPath()).isEqualTo("$[1]");
reader.peek();
JsonToken unused4 = reader.peek();
assertThat(reader.getPreviousPath()).isEqualTo("$[0]");
assertThat(reader.getPath()).isEqualTo("$[1]");
reader.nextInt();
int unused5 = reader.nextInt();
assertThat(reader.getPreviousPath()).isEqualTo("$[1]");
assertThat(reader.getPath()).isEqualTo("$[2]");
reader.peek();
JsonToken unused6 = reader.peek();
assertThat(reader.getPreviousPath()).isEqualTo("$[1]");
assertThat(reader.getPath()).isEqualTo("$[2]");
reader.endArray();
assertThat(reader.getPreviousPath()).isEqualTo("$");
assertThat(reader.getPath()).isEqualTo("$");
reader.peek();
JsonToken unused7 = reader.peek();
assertThat(reader.getPreviousPath()).isEqualTo("$");
assertThat(reader.getPath()).isEqualTo("$");
reader.close();
@ -249,11 +249,11 @@ public class JsonReaderPathTest {
reader.beginObject();
assertThat(reader.getPreviousPath()).isEqualTo("$.");
assertThat(reader.getPath()).isEqualTo("$.");
reader.nextName();
String unused1 = reader.nextName();
reader.skipValue();
assertThat(reader.getPreviousPath()).isEqualTo("$.a");
assertThat(reader.getPath()).isEqualTo("$.a");
reader.nextName();
String unused2 = reader.nextName();
assertThat(reader.getPreviousPath()).isEqualTo("$.b");
assertThat(reader.getPath()).isEqualTo("$.b");
}
@ -261,7 +261,7 @@ public class JsonReaderPathTest {
@Test public void skipObjectEnd() throws IOException {
JsonReader reader = factory.create("{\"a\":{},\"b\":2}");
reader.beginObject();
reader.nextName();
String unused = reader.nextName();
reader.beginObject();
assertThat(reader.getPreviousPath()).isEqualTo("$.a.");
assertThat(reader.getPath()).isEqualTo("$.a.");
@ -353,37 +353,37 @@ public class JsonReaderPathTest {
reader.beginObject();
assertThat(reader.getPreviousPath()).isEqualTo("$.");
assertThat(reader.getPath()).isEqualTo("$.");
reader.nextName();
String unused1 = reader.nextName();
assertThat(reader.getPreviousPath()).isEqualTo("$.a");
assertThat(reader.getPath()).isEqualTo("$.a");
reader.beginObject();
assertThat(reader.getPreviousPath()).isEqualTo("$.a.");
assertThat(reader.getPath()).isEqualTo("$.a.");
reader.nextName();
String unused2 = reader.nextName();
assertThat(reader.getPreviousPath()).isEqualTo("$.a.a1");
assertThat(reader.getPath()).isEqualTo("$.a.a1");
reader.nextInt();
int unused3 = reader.nextInt();
assertThat(reader.getPreviousPath()).isEqualTo("$.a.a1");
assertThat(reader.getPath()).isEqualTo("$.a.a1");
reader.nextName();
String unused4 = reader.nextName();
assertThat(reader.getPreviousPath()).isEqualTo("$.a.a2");
assertThat(reader.getPath()).isEqualTo("$.a.a2");
reader.nextInt();
int unused5 = reader.nextInt();
assertThat(reader.getPreviousPath()).isEqualTo("$.a.a2");
assertThat(reader.getPath()).isEqualTo("$.a.a2");
reader.endObject();
assertThat(reader.getPreviousPath()).isEqualTo("$.a");
assertThat(reader.getPath()).isEqualTo("$.a");
reader.nextName();
String unused6 = reader.nextName();
assertThat(reader.getPreviousPath()).isEqualTo("$.b");
assertThat(reader.getPath()).isEqualTo("$.b");
reader.beginObject();
assertThat(reader.getPreviousPath()).isEqualTo("$.b.");
assertThat(reader.getPath()).isEqualTo("$.b.");
reader.nextName();
String unused7 = reader.nextName();
assertThat(reader.getPreviousPath()).isEqualTo("$.b.b1");
assertThat(reader.getPath()).isEqualTo("$.b.b1");
reader.nextInt();
int unused8 = reader.nextInt();
assertThat(reader.getPreviousPath()).isEqualTo("$.b.b1");
assertThat(reader.getPath()).isEqualTo("$.b.b1");
reader.endObject();

View File

@ -33,6 +33,7 @@ import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.Arrays;
import com.google.gson.stream.JsonToken;
import org.junit.Ignore;
import org.junit.Test;
@ -855,8 +856,8 @@ public final class JsonReaderTest {
try {
JsonReader reader = new JsonReader(reader("{\"a\":true}"));
reader.beginObject();
reader.nextName();
reader.peek();
String unused1 = reader.nextName();
JsonToken unused2 = reader.peek();
reader.close();
reader.nextBoolean();
fail();
@ -869,13 +870,13 @@ public final class JsonReaderTest {
JsonReader reader = new JsonReader(reader("{\"a\":true}"));
reader.beginObject();
try {
reader.nextString();
String unused = reader.nextString();
fail();
} catch (IllegalStateException expected) {
}
assertThat(reader.nextName()).isEqualTo("a");
try {
reader.nextName();
String unused = reader.nextName();
fail();
} catch (IllegalStateException expected) {
}
@ -1234,8 +1235,8 @@ public final class JsonReaderTest {
JsonReader reader = new JsonReader(reader("[true;true]"));
reader.beginArray();
try {
reader.nextBoolean();
reader.nextBoolean();
boolean unused1 = reader.nextBoolean();
boolean unused2 = reader.nextBoolean();
fail();
} catch (IOException expected) {
}
@ -1268,8 +1269,8 @@ public final class JsonReaderTest {
reader.beginObject();
assertThat(reader.nextName()).isEqualTo("a");
try {
reader.nextBoolean();
reader.nextName();
boolean unused1 = reader.nextBoolean();
String unused2 = reader.nextName();
fail();
} catch (IOException expected) {
}
@ -1601,9 +1602,9 @@ public final class JsonReaderTest {
JsonReader reader1 = new JsonReader(reader(json));
reader1.setLenient(true);
reader1.beginArray();
reader1.nextString();
String unused1 = reader1.nextString();
try {
reader1.peek();
JsonToken unused2 = reader1.peek();
fail();
} catch (IOException expected) {
assertThat(expected.getMessage()).isEqualTo(message);
@ -1615,7 +1616,7 @@ public final class JsonReaderTest {
reader2.beginArray();
reader2.skipValue();
try {
reader2.peek();
JsonToken unused3 = reader2.peek();
fail();
} catch (IOException expected) {
assertThat(expected.getMessage()).isEqualTo(message);
@ -1626,14 +1627,14 @@ public final class JsonReaderTest {
public void testFailWithPositionDeepPath() throws IOException {
JsonReader reader = new JsonReader(reader("[1,{\"a\":[2,3,}"));
reader.beginArray();
reader.nextInt();
int unused1 = reader.nextInt();
reader.beginObject();
reader.nextName();
String unused2 = reader.nextName();
reader.beginArray();
reader.nextInt();
reader.nextInt();
int unused3 = reader.nextInt();
int unused4 = reader.nextInt();
try {
reader.peek();
JsonToken unused5 = reader.peek();
fail();
} catch (IOException expected) {
assertThat(expected.getMessage()).isEqualTo("Expected value at line 1 column 14 path $[1].a[2]");

View File

@ -20,6 +20,7 @@ import static java.util.Objects.requireNonNull;
import com.google.common.base.CaseFormat;
import com.google.common.collect.MapMaker;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
@ -102,6 +103,7 @@ public class ProtoTypeAdapter
setFieldNameSerializationFormat(fromFieldNameFormat, toFieldNameFormat);
}
@CanIgnoreReturnValue
public Builder setEnumSerialization(EnumSerialization enumSerialization) {
this.enumSerialization = requireNonNull(enumSerialization);
return this;
@ -122,6 +124,7 @@ public class ProtoTypeAdapter
* n__id_ct nIdCt
* }</pre>
*/
@CanIgnoreReturnValue
public Builder setFieldNameSerializationFormat(CaseFormat fromFieldNameFormat,
CaseFormat toFieldNameFormat) {
this.protoFormat = fromFieldNameFormat;
@ -141,6 +144,7 @@ public class ProtoTypeAdapter
* ...the adapter will serialize the field using '{@code appId}' instead of the default '
* {@code clientAppId}'. This lets you customize the name serialization of any proto field.
*/
@CanIgnoreReturnValue
public Builder addSerializedNameExtension(
Extension<FieldOptions, String> serializedNameExtension) {
serializedNameExtensions.add(requireNonNull(serializedNameExtension));
@ -166,6 +170,7 @@ public class ProtoTypeAdapter
* Note that you need to set the enum serialization of this adapter to
* {@link EnumSerialization#NAME}, otherwise these annotations will be ignored.
*/
@CanIgnoreReturnValue
public Builder addSerializedEnumValueExtension(
Extension<EnumValueOptions, String> serializedEnumValueExtension) {
serializedEnumValueExtensions.add(requireNonNull(serializedEnumValueExtension));