Skip to content

Commit 08174e2

Browse files
authored
Perform minor code clean-up (#2544)
* Perform minor code clean-up Notable changes: - Replace most usages of `<code>` with `{@code ...}` in Javadoc - Add proper summary sentence to `GsonBuilder.enableComplexMapKeySerialization` - Extend documentation for `GsonBuilder.setDateFormat` methods - Fix `TypeToken.isAssignableFrom(Type)` throwing AssertionError in some cases Maybe the method should not throw an exception in the first place, but it might not matter much since it is deprecated already anyway. - Remove outdated `throws NumberFormatException` from internal `JsonReader.nextQuotedValue`; the behavior had been changed by 85ebaf7 - Fix incorrect documentation on JsonScope fields - Fix unit tests having 'expected' and 'actual' switched - Use dedicated Truth methods instead of `isTrue()` / `isFalse()` - Use common helper methods in JsonWriterTest to avoid duplication * Implement `toString()` for ReflectionAccessFilter constants * Address most of the review comments * Add comment about `source.scm.tag=HEAD` warning Actually it looks like the warning is not actually caused by usage of `HEAD` as value, but rather because the project has a snapshot version during development (which is expected though), see https://github.com/apache/maven-artifact-plugin/blob/maven-artifact-plugin-3.5.0/src/main/java/org/apache/maven/plugins/artifact/buildinfo/BuildInfoWriter.java#L140 But this is not a problem either since during release a non-snapshot version is used.
1 parent 6684726 commit 08174e2

36 files changed

+204
-254
lines changed

examples/android-proguard-example/src/com/google/gson/examples/android/GsonProguardExampleActivity.java

+4-4
Original file line numberDiff line numberDiff line change
@@ -41,13 +41,13 @@ public void onCreate(Bundle icicle) {
4141
Cart cart = buildCart();
4242
StringBuilder sb = new StringBuilder();
4343
sb.append("Gson.toJson() example: \n");
44-
sb.append(" Cart Object: ").append(cart).append("\n");
45-
sb.append(" Cart JSON: ").append(gson.toJson(cart)).append("\n");
44+
sb.append(" Cart Object: ").append(cart).append('\n');
45+
sb.append(" Cart JSON: ").append(gson.toJson(cart)).append('\n');
4646
sb.append("\n\nGson.fromJson() example: \n");
4747
String json = "{buyer:'Happy Camper',creditCard:'4111-1111-1111-1111',"
4848
+ "lineItems:[{name:'nails',priceInMicros:100000,quantity:100,currencyCode:'USD'}]}";
49-
sb.append("Cart JSON: ").append(json).append("\n");
50-
sb.append("Cart Object: ").append(gson.fromJson(json, Cart.class)).append("\n");
49+
sb.append("Cart JSON: ").append(json).append('\n');
50+
sb.append("Cart Object: ").append(gson.fromJson(json, Cart.class)).append('\n');
5151
tv.setText(sb.toString());
5252
tv.invalidate();
5353
}

gson/src/main/java/com/google/gson/Gson.java

+11-12
Original file line numberDiff line numberDiff line change
@@ -216,9 +216,9 @@ public final class Gson {
216216
* following settings:
217217
*
218218
* <ul>
219-
* <li>The JSON generated by <code>toJson</code> methods is in compact representation. This
220-
* means that all the unneeded white-space is removed. You can change this behavior with
221-
* {@link GsonBuilder#setPrettyPrinting()}.
219+
* <li>The JSON generated by {@code toJson} methods is in compact representation. This means
220+
* that all the unneeded white-space is removed. You can change this behavior with {@link
221+
* GsonBuilder#setPrettyPrinting()}.
222222
* <li>When the JSON generated contains more than one line, the kind of newline and indent to
223223
* use can be configured with {@link GsonBuilder#setFormattingStyle(FormattingStyle)}.
224224
* <li>The generated JSON omits all the fields that are null. Note that nulls in arrays are kept
@@ -240,13 +240,12 @@ public final class Gson {
240240
* <li>By default, Gson ignores the {@link com.google.gson.annotations.Since} annotation. You
241241
* can enable Gson to use this annotation through {@link GsonBuilder#setVersion(double)}.
242242
* <li>The default field naming policy for the output JSON is same as in Java. So, a Java class
243-
* field <code>versionNumber</code> will be output as <code>&quot;versionNumber&quot;</code>
244-
* in JSON. The same rules are applied for mapping incoming JSON to the Java classes. You
245-
* can change this policy through {@link
246-
* GsonBuilder#setFieldNamingPolicy(FieldNamingPolicy)}.
247-
* <li>By default, Gson excludes <code>transient</code> or <code>static</code> fields from
248-
* consideration for serialization and deserialization. You can change this behavior through
249-
* {@link GsonBuilder#excludeFieldsWithModifiers(int...)}.
243+
* field {@code versionNumber} will be output as {@code "versionNumber"} in JSON. The same
244+
* rules are applied for mapping incoming JSON to the Java classes. You can change this
245+
* policy through {@link GsonBuilder#setFieldNamingPolicy(FieldNamingPolicy)}.
246+
* <li>By default, Gson excludes {@code transient} or {@code static} fields from consideration
247+
* for serialization and deserialization. You can change this behavior through {@link
248+
* GsonBuilder#excludeFieldsWithModifiers(int...)}.
250249
* <li>No explicit strictness is set. You can change this by calling {@link
251250
* GsonBuilder#setStrictness(Strictness)}.
252251
* </ul>
@@ -665,8 +664,8 @@ public <T> TypeAdapter<T> getAdapter(TypeToken<T> type) {
665664
* is an example:
666665
*
667666
* <p>Let's say we want to write a type adapter that counts the number of objects being read from
668-
* or written to JSON. We can achieve this by writing a type adapter factory that uses the <code>
669-
* getDelegateAdapter</code> method:
667+
* or written to JSON. We can achieve this by writing a type adapter factory that uses the {@code
668+
* getDelegateAdapter} method:
670669
*
671670
* <pre>{@code
672671
* class StatsTypeAdapterFactory implements TypeAdapterFactory {

gson/src/main/java/com/google/gson/GsonBuilder.java

+20-18
Original file line numberDiff line numberDiff line change
@@ -227,8 +227,8 @@ public GsonBuilder excludeFieldsWithoutExposeAnnotation() {
227227
}
228228

229229
/**
230-
* Configure Gson to serialize null fields. By default, Gson omits all fields that are null during
231-
* serialization.
230+
* Configures Gson to serialize null fields. By default, Gson omits all fields that are null
231+
* during serialization.
232232
*
233233
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
234234
* @since 1.2
@@ -240,10 +240,11 @@ public GsonBuilder serializeNulls() {
240240
}
241241

242242
/**
243-
* Enabling this feature will only change the serialized form if the map key is a complex type
244-
* (i.e. non-primitive) in its <strong>serialized</strong> JSON form. The default implementation
245-
* of map serialization uses {@code toString()} on the key; however, when this is called then one
246-
* of the following cases apply:
243+
* Configures Gson to serialize {@code Map} objects with complex keys as JSON arrays. Enabling
244+
* this feature will only change the serialized form if the map key is a complex type (i.e.
245+
* non-primitive) in its <strong>serialized</strong> JSON form. The default implementation of map
246+
* serialization uses {@code toString()} on the key; however, when this is called then one of the
247+
* following cases apply:
247248
*
248249
* <p><b>Maps as JSON objects</b>
249250
*
@@ -622,23 +623,24 @@ private static int checkDateFormatStyle(int style) {
622623
}
623624

624625
/**
625-
* Configures Gson to serialize {@code Date} objects according to the style value provided. You
626-
* can call this method or {@link #setDateFormat(String)} multiple times, but only the last
627-
* invocation will be used to decide the serialization format.
626+
* Configures Gson to serialize {@code Date} objects according to the date style value provided.
627+
* You can call this method or {@link #setDateFormat(String)} multiple times, but only the last
628+
* invocation will be used to decide the serialization format. This methods leaves the current
629+
* 'time style' unchanged.
628630
*
629-
* <p>Note that this style value should be one of the predefined constants in the {@code
630-
* DateFormat} class. See the documentation in {@link java.text.DateFormat} for more information
631-
* on the valid style constants.
631+
* <p>Note that this style value should be one of the predefined constants in the {@link
632+
* DateFormat} class, such as {@link DateFormat#MEDIUM}. See the documentation of the {@link
633+
* DateFormat} class for more information on the valid style constants.
632634
*
633-
* @param style the predefined date style that date objects will be serialized/deserialized
635+
* @param dateStyle the predefined date style that date objects will be serialized/deserialized
634636
* to/from
635637
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
636638
* @throws IllegalArgumentException if the style is invalid
637639
* @since 1.2
638640
*/
639641
@CanIgnoreReturnValue
640-
public GsonBuilder setDateFormat(int style) {
641-
this.dateStyle = checkDateFormatStyle(style);
642+
public GsonBuilder setDateFormat(int dateStyle) {
643+
this.dateStyle = checkDateFormatStyle(dateStyle);
642644
this.datePattern = null;
643645
return this;
644646
}
@@ -648,9 +650,9 @@ public GsonBuilder setDateFormat(int style) {
648650
* can call this method or {@link #setDateFormat(String)} multiple times, but only the last
649651
* invocation will be used to decide the serialization format.
650652
*
651-
* <p>Note that this style value should be one of the predefined constants in the {@code
652-
* DateFormat} class. See the documentation in {@link java.text.DateFormat} for more information
653-
* on the valid style constants.
653+
* <p>Note that this style value should be one of the predefined constants in the {@link
654+
* DateFormat} class, such as {@link DateFormat#MEDIUM}. See the documentation of the {@link
655+
* DateFormat} class for more information on the valid style constants.
654656
*
655657
* @param dateStyle the predefined date style that date objects will be serialized/deserialized
656658
* to/from

gson/src/main/java/com/google/gson/ReflectionAccessFilter.java

+20
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,11 @@ public FilterResult check(Class<?> rawClass) {
117117
? FilterResult.BLOCK_INACCESSIBLE
118118
: FilterResult.INDECISIVE;
119119
}
120+
121+
@Override
122+
public String toString() {
123+
return "ReflectionAccessFilter#BLOCK_INACCESSIBLE_JAVA";
124+
}
120125
};
121126

122127
/**
@@ -143,6 +148,11 @@ public FilterResult check(Class<?> rawClass) {
143148
? FilterResult.BLOCK_ALL
144149
: FilterResult.INDECISIVE;
145150
}
151+
152+
@Override
153+
public String toString() {
154+
return "ReflectionAccessFilter#BLOCK_ALL_JAVA";
155+
}
146156
};
147157

148158
/**
@@ -169,6 +179,11 @@ public FilterResult check(Class<?> rawClass) {
169179
? FilterResult.BLOCK_ALL
170180
: FilterResult.INDECISIVE;
171181
}
182+
183+
@Override
184+
public String toString() {
185+
return "ReflectionAccessFilter#BLOCK_ALL_ANDROID";
186+
}
172187
};
173188

174189
/**
@@ -196,6 +211,11 @@ public FilterResult check(Class<?> rawClass) {
196211
? FilterResult.BLOCK_ALL
197212
: FilterResult.INDECISIVE;
198213
}
214+
215+
@Override
216+
public String toString() {
217+
return "ReflectionAccessFilter#BLOCK_ALL_PLATFORM";
218+
}
199219
};
200220

201221
/**

gson/src/main/java/com/google/gson/TypeAdapter.java

+5-5
Original file line numberDiff line numberDiff line change
@@ -68,11 +68,11 @@
6868
* #write(JsonWriter,Object) write()} must write exactly one value. For primitive types this is
6969
* means readers should make exactly one call to {@code nextBoolean()}, {@code nextDouble()}, {@code
7070
* nextInt()}, {@code nextLong()}, {@code nextString()} or {@code nextNull()}. Writers should make
71-
* exactly one call to one of <code>value()</code> or <code>nullValue()</code>. For arrays, type
72-
* adapters should start with a call to {@code beginArray()}, convert all elements, and finish with
73-
* a call to {@code endArray()}. For objects, they should start with {@code beginObject()}, convert
74-
* the object, and finish with {@code endObject()}. Failing to convert a value or converting too
75-
* many values may cause the application to crash.
71+
* exactly one call to one of {@code value()} or {@code nullValue()}. For arrays, type adapters
72+
* should start with a call to {@code beginArray()}, convert all elements, and finish with a call to
73+
* {@code endArray()}. For objects, they should start with {@code beginObject()}, convert the
74+
* object, and finish with {@code endObject()}. Failing to convert a value or converting too many
75+
* values may cause the application to crash.
7676
*
7777
* <p>Type adapters should be prepared to read null from the stream and write it to the stream.
7878
* Alternatively, they should use {@link #nullSafe()} method while registering the type adapter with

gson/src/main/java/com/google/gson/reflect/TypeToken.java

+6-6
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,7 @@ public boolean isAssignableFrom(Type from) {
200200
return rawType.isAssignableFrom($Gson$Types.getRawType(from))
201201
&& isAssignableFrom(from, (GenericArrayType) type);
202202
} else {
203-
throw buildUnexpectedTypeError(
203+
throw buildUnsupportedTypeException(
204204
type, Class.class, ParameterizedType.class, GenericArrayType.class);
205205
}
206206
}
@@ -309,21 +309,21 @@ private static boolean typeEquals(
309309
return false;
310310
}
311311

312-
private static AssertionError buildUnexpectedTypeError(Type token, Class<?>... expected) {
312+
private static IllegalArgumentException buildUnsupportedTypeException(
313+
Type token, Class<?>... expected) {
313314

314315
// Build exception message
315-
StringBuilder exceptionMessage = new StringBuilder("Unexpected type. Expected one of: ");
316+
StringBuilder exceptionMessage = new StringBuilder("Unsupported type, expected one of: ");
316317
for (Class<?> clazz : expected) {
317318
exceptionMessage.append(clazz.getName()).append(", ");
318319
}
319320
exceptionMessage
320321
.append("but got: ")
321322
.append(token.getClass().getName())
322323
.append(", for type token: ")
323-
.append(token.toString())
324-
.append('.');
324+
.append(token.toString());
325325

326-
return new AssertionError(exceptionMessage.toString());
326+
return new IllegalArgumentException(exceptionMessage.toString());
327327
}
328328

329329
/**

gson/src/main/java/com/google/gson/stream/JsonReader.java

+5-6
Original file line numberDiff line numberDiff line change
@@ -1056,7 +1056,6 @@ public long nextLong() throws IOException {
10561056
* consumes the closing quote, but does not include it in the returned string.
10571057
*
10581058
* @param quote either ' or ".
1059-
* @throws NumberFormatException if any unicode escape sequences are malformed.
10601059
*/
10611060
private String nextQuotedValue(char quote) throws IOException {
10621061
// Like nextNonWhitespace, this uses locals 'p' and 'l' to save inner-loop field access.
@@ -1527,7 +1526,7 @@ private int nextNonWhitespace(boolean throwOnEof) throws IOException {
15271526
}
15281527
}
15291528

1530-
private void checkLenient() throws IOException {
1529+
private void checkLenient() throws MalformedJsonException {
15311530
if (strictness != Strictness.LENIENT) {
15321531
throw syntaxError(
15331532
"Use JsonReader.setStrictness(Strictness.LENIENT) to accept malformed JSON");
@@ -1655,7 +1654,7 @@ public String getPath() {
16551654
* backslash. The backslash '\' should have already been read. This supports both Unicode escapes
16561655
* "u000A" and two-character escapes "\n".
16571656
*
1658-
* @throws MalformedJsonException if any Unicode escape sequences are malformed.
1657+
* @throws MalformedJsonException if the escape sequence is malformed
16591658
*/
16601659
@SuppressWarnings("fallthrough")
16611660
private char readEscapeCharacter() throws IOException {
@@ -1725,10 +1724,10 @@ private char readEscapeCharacter() throws IOException {
17251724
}
17261725

17271726
/**
1728-
* Throws a new IO exception with the given message and a context snippet with this reader's
1729-
* content.
1727+
* Throws a new {@link MalformedJsonException} with the given message and information about the
1728+
* current location.
17301729
*/
1731-
private IOException syntaxError(String message) throws IOException {
1730+
private MalformedJsonException syntaxError(String message) throws MalformedJsonException {
17321731
throw new MalformedJsonException(
17331732
message + locationString() + "\nSee " + TroubleshootingGuide.createUrl("malformed-json"));
17341733
}

gson/src/main/java/com/google/gson/stream/JsonScope.java

+6-9
Original file line numberDiff line numberDiff line change
@@ -24,28 +24,25 @@
2424
*/
2525
final class JsonScope {
2626

27-
/** An array with no elements requires no separators or newlines before it is closed. */
27+
/** An array with no elements requires no separator before the next element. */
2828
static final int EMPTY_ARRAY = 1;
2929

30-
/** An array with at least one value requires a comma and newline before the next element. */
30+
/** An array with at least one value requires a separator before the next element. */
3131
static final int NONEMPTY_ARRAY = 2;
3232

33-
/** An object with no name/value pairs requires no separators or newlines before it is closed. */
33+
/** An object with no name/value pairs requires no separator before the next element. */
3434
static final int EMPTY_OBJECT = 3;
3535

3636
/** An object whose most recent element is a key. The next element must be a value. */
3737
static final int DANGLING_NAME = 4;
3838

39-
/**
40-
* An object with at least one name/value pair requires a comma and newline before the next
41-
* element.
42-
*/
39+
/** An object with at least one name/value pair requires a separator before the next element. */
4340
static final int NONEMPTY_OBJECT = 5;
4441

45-
/** No object or array has been started. */
42+
/** No top-level value has been started yet. */
4643
static final int EMPTY_DOCUMENT = 6;
4744

48-
/** A document with at an array or object. */
45+
/** A top-level value has already been started. */
4946
static final int NONEMPTY_DOCUMENT = 7;
5047

5148
/** A document that's been closed and cannot be accessed. */

gson/src/main/java/com/google/gson/stream/JsonWriter.java

+3-3
Original file line numberDiff line numberDiff line change
@@ -356,9 +356,9 @@ public final Strictness getStrictness() {
356356

357357
/**
358358
* Configures this writer to emit JSON that's safe for direct inclusion in HTML and XML documents.
359-
* This escapes the HTML characters {@code <}, {@code >}, {@code &} and {@code =} before writing
360-
* them to the stream. Without this setting, your XML/HTML encoder should replace these characters
361-
* with the corresponding escape sequences.
359+
* This escapes the HTML characters {@code <}, {@code >}, {@code &}, {@code =} and {@code '}
360+
* before writing them to the stream. Without this setting, your XML/HTML encoder should replace
361+
* these characters with the corresponding escape sequences.
362362
*/
363363
public final void setHtmlSafe(boolean htmlSafe) {
364364
this.htmlSafe = htmlSafe;

gson/src/test/java/com/google/gson/JsonPrimitiveTest.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -297,7 +297,7 @@ public void testEqualsAcrossTypes() {
297297
new JsonPrimitive(new BigInteger("0")), new JsonPrimitive(0));
298298
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(0), new JsonPrimitive(0L));
299299
MoreAsserts.assertEqualsAndHashCode(
300-
new JsonPrimitive(new BigInteger("0")), new JsonPrimitive(0));
300+
new JsonPrimitive(new BigDecimal("0")), new JsonPrimitive(0));
301301
MoreAsserts.assertEqualsAndHashCode(
302302
new JsonPrimitive(Float.NaN), new JsonPrimitive(Double.NaN));
303303
}

gson/src/test/java/com/google/gson/MixedStreamTest.java

+3-5
Original file line numberDiff line numberDiff line change
@@ -74,11 +74,9 @@ public void testReadMixedStreamed() throws IOException {
7474
JsonReader jsonReader = new JsonReader(stringReader);
7575

7676
jsonReader.beginArray();
77-
// actual and expected object are inverted in the test.
78-
// gson.fromJson(jsonReader, Car.class) as arg of assertThat() cause an ambiguous method call
79-
assertThat(BLUE_MUSTANG).isEqualTo(gson.fromJson(jsonReader, Car.class));
80-
assertThat(BLACK_BMW).isEqualTo(gson.fromJson(jsonReader, Car.class));
81-
assertThat(RED_MIATA).isEqualTo(gson.fromJson(jsonReader, Car.class));
77+
assertThat(gson.<Car>fromJson(jsonReader, Car.class)).isEqualTo(BLUE_MUSTANG);
78+
assertThat(gson.<Car>fromJson(jsonReader, Car.class)).isEqualTo(BLACK_BMW);
79+
assertThat(gson.<Car>fromJson(jsonReader, Car.class)).isEqualTo(RED_MIATA);
8280
jsonReader.endArray();
8381
}
8482

gson/src/test/java/com/google/gson/MockExclusionStrategy.java

-42
This file was deleted.

0 commit comments

Comments
 (0)