Fail Maven build on compiler warnings; remove some warning suppressions (#2183)

* Fail Maven build on compiler warnings; remove some warning suppressions

* Fix compiler warnings causing failure for newer JDK

* Improve placement of "raw" and "unchecked" warning suppressions

* Adjust javac documentation link

* Fix compilation error on newer JDKs
This commit is contained in:
Marcono1234 2022-08-27 02:36:18 +02:00 committed by GitHub
parent 325f37cd6b
commit f7a164d98b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
30 changed files with 164 additions and 168 deletions

View File

@ -42,7 +42,6 @@ import java.util.Queue;
* Writes a graph of objects as a list of named nodes.
*/
// TODO: proper documentation
@SuppressWarnings("rawtypes")
public final class GraphAdapterBuilder {
private final Map<Type, InstanceCreator<?>> instanceCreators;
private final ConstructorConstructor constructorConstructor;
@ -78,7 +77,7 @@ public final class GraphAdapterBuilder {
}
}
static class Factory implements TypeAdapterFactory, InstanceCreator {
static class Factory implements TypeAdapterFactory, InstanceCreator<Object> {
private final Map<Type, InstanceCreator<?>> instanceCreators;
private final ThreadLocal<Graph> graphThreadLocal = new ThreadLocal<>();
@ -215,7 +214,6 @@ public final class GraphAdapterBuilder {
* <p>Gson should only ever call this method when we're expecting it to;
* that is only when we've called back into Gson to deserialize a tree.
*/
@SuppressWarnings("unchecked")
@Override
public Object createInstance(Type type) {
Graph graph = graphThreadLocal.get();
@ -242,14 +240,14 @@ public final class GraphAdapterBuilder {
* The queue of elements to write during serialization. Unused during
* deserialization.
*/
private final Queue<Element> queue = new LinkedList<>();
private final Queue<Element<?>> queue = new LinkedList<>();
/**
* The instance currently being deserialized. Used as a backdoor between
* the graph traversal (which needs to know instances) and instance creators
* which create them.
*/
private Element nextCreate;
private Element<Object> nextCreate;
private Graph(Map<Object, Element<?>> map) {
this.map = map;
@ -299,11 +297,12 @@ public final class GraphAdapterBuilder {
typeAdapter.write(out, value);
}
@SuppressWarnings("unchecked")
void read(Graph graph) throws IOException {
if (graph.nextCreate != null) {
throw new IllegalStateException("Unexpected recursive call to read() for " + id);
}
graph.nextCreate = this;
graph.nextCreate = (Element<Object>) this;
value = typeAdapter.fromJsonTree(element);
if (value == null) {
throw new IllegalStateException("non-null value deserialized to null: " + element);

View File

@ -16,15 +16,12 @@
package com.google.gson.typeadapters;
import javax.annotation.PostConstruct;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import junit.framework.TestCase;
import java.util.Arrays;
import java.util.List;
import javax.annotation.PostConstruct;
import junit.framework.TestCase;
public class PostConstructAdapterFactoryTest extends TestCase {
public void test() throws Exception {
@ -55,6 +52,7 @@ public class PostConstructAdapterFactoryTest extends TestCase {
assertEquals(sandwiches, sandwichesFromJson);
}
@SuppressWarnings("overrides") // for missing hashCode() override
static class Sandwich {
public String bread;
public String cheese;
@ -89,6 +87,7 @@ public class PostConstructAdapterFactoryTest extends TestCase {
}
}
@SuppressWarnings("overrides") // for missing hashCode() override
static class MultipleSandwiches {
public List<Sandwich> sandwiches;

View File

@ -503,12 +503,13 @@ public final class Gson {
* @throws IllegalArgumentException if this GSON cannot serialize and
* deserialize {@code type}.
*/
@SuppressWarnings("unchecked")
public <T> TypeAdapter<T> getAdapter(TypeToken<T> type) {
Objects.requireNonNull(type, "type must not be null");
TypeAdapter<?> cached = typeTokenCache.get(type);
if (cached != null) {
return (TypeAdapter<T>) cached;
@SuppressWarnings("unchecked")
TypeAdapter<T> adapter = (TypeAdapter<T>) cached;
return adapter;
}
Map<TypeToken<?>, FutureTypeAdapter<?>> threadCalls = calls.get();
@ -520,6 +521,7 @@ public final class Gson {
}
// the key and value type parameters always agree
@SuppressWarnings("unchecked")
FutureTypeAdapter<T> ongoingCall = (FutureTypeAdapter<T>) threadCalls.get(type);
if (ongoingCall != null) {
return ongoingCall;
@ -532,6 +534,7 @@ public final class Gson {
for (TypeAdapterFactory factory : factories) {
TypeAdapter<T> candidate = factory.create(this, type);
if (candidate != null) {
@SuppressWarnings("unchecked")
TypeAdapter<T> existingAdapter = (TypeAdapter<T>) typeTokenCache.putIfAbsent(type, candidate);
// If other thread concurrently added adapter prefer that one instead
if (existingAdapter != null) {
@ -780,9 +783,9 @@ public final class Gson {
*
* @throws JsonIOException if there was a problem writing to the writer
*/
@SuppressWarnings("unchecked")
public void toJson(Object src, Type typeOfSrc, JsonWriter writer) throws JsonIOException {
TypeAdapter<?> adapter = getAdapter(TypeToken.get(typeOfSrc));
@SuppressWarnings("unchecked")
TypeAdapter<Object> adapter = (TypeAdapter<Object>) getAdapter(TypeToken.get(typeOfSrc));
boolean oldLenient = writer.isLenient();
writer.setLenient(true);
boolean oldHtmlSafe = writer.isHtmlSafe();
@ -790,7 +793,7 @@ public final class Gson {
boolean oldSerializeNulls = writer.getSerializeNulls();
writer.setSerializeNulls(serializeNulls);
try {
((TypeAdapter<Object>) adapter).write(writer, src);
adapter.write(writer, src);
} catch (IOException e) {
throw new JsonIOException(e);
} catch (AssertionError e) {
@ -957,12 +960,12 @@ public final class Gson {
* @throws JsonParseException if json is not a valid representation for an object of type typeOfT
* @throws JsonSyntaxException if json is not a valid representation for an object of type
*/
@SuppressWarnings("unchecked")
public <T> T fromJson(String json, Type typeOfT) throws JsonSyntaxException {
if (json == null) {
return null;
}
StringReader reader = new StringReader(json);
@SuppressWarnings("unchecked")
T target = (T) fromJson(reader, typeOfT);
return target;
}
@ -1017,9 +1020,9 @@ public final class Gson {
* @throws JsonSyntaxException if json is not a valid representation for an object of type
* @since 1.2
*/
@SuppressWarnings("unchecked")
public <T> T fromJson(Reader json, Type typeOfT) throws JsonIOException, JsonSyntaxException {
JsonReader jsonReader = newJsonReader(json);
@SuppressWarnings("unchecked")
T object = (T) fromJson(jsonReader, typeOfT);
assertFullConsumption(object, jsonReader);
return object;
@ -1052,7 +1055,6 @@ public final class Gson {
* @throws JsonIOException if there was a problem writing to the Reader
* @throws JsonSyntaxException if json is not a valid representation for an object of type
*/
@SuppressWarnings("unchecked")
public <T> T fromJson(JsonReader reader, Type typeOfT) throws JsonIOException, JsonSyntaxException {
boolean isEmpty = true;
boolean oldLenient = reader.isLenient();
@ -1060,6 +1062,7 @@ public final class Gson {
try {
reader.peek();
isEmpty = false;
@SuppressWarnings("unchecked")
TypeToken<T> typeToken = (TypeToken<T>) TypeToken.get(typeOfT);
TypeAdapter<T> typeAdapter = getAdapter(typeToken);
T object = typeAdapter.read(reader);

View File

@ -541,7 +541,6 @@ 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
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public GsonBuilder registerTypeAdapter(Type type, Object typeAdapter) {
Objects.requireNonNull(type);
$Gson$Preconditions.checkArgument(typeAdapter instanceof JsonSerializer<?>
@ -549,14 +548,16 @@ public final class GsonBuilder {
|| typeAdapter instanceof InstanceCreator<?>
|| typeAdapter instanceof TypeAdapter<?>);
if (typeAdapter instanceof InstanceCreator<?>) {
instanceCreators.put(type, (InstanceCreator) typeAdapter);
instanceCreators.put(type, (InstanceCreator<?>) typeAdapter);
}
if (typeAdapter instanceof JsonSerializer<?> || typeAdapter instanceof JsonDeserializer<?>) {
TypeToken<?> typeToken = TypeToken.get(type);
factories.add(TreeTypeAdapter.newFactoryWithMatchRawType(typeToken, typeAdapter));
}
if (typeAdapter instanceof TypeAdapter<?>) {
factories.add(TypeAdapters.newFactory(TypeToken.get(type), (TypeAdapter)typeAdapter));
@SuppressWarnings({"unchecked", "rawtypes"})
TypeAdapterFactory factory = TypeAdapters.newFactory(TypeToken.get(type), (TypeAdapter)typeAdapter);
factories.add(factory);
}
return this;
}
@ -589,7 +590,6 @@ public final class GsonBuilder {
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
* @since 1.7
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public GsonBuilder registerTypeHierarchyAdapter(Class<?> baseType, Object typeAdapter) {
Objects.requireNonNull(baseType);
$Gson$Preconditions.checkArgument(typeAdapter instanceof JsonSerializer<?>
@ -599,7 +599,9 @@ public final class GsonBuilder {
hierarchyFactories.add(TreeTypeAdapter.newTypeHierarchyFactory(baseType, typeAdapter));
}
if (typeAdapter instanceof TypeAdapter<?>) {
factories.add(TypeAdapters.newTypeHierarchyFactory(baseType, (TypeAdapter)typeAdapter));
@SuppressWarnings({"unchecked", "rawtypes"})
TypeAdapterFactory factory = TypeAdapters.newTypeHierarchyFactory(baseType, (TypeAdapter)typeAdapter);
factories.add(factory);
}
return this;
}

View File

@ -26,6 +26,7 @@ import java.math.BigDecimal;
*
* @author Inderjeet Singh
*/
@SuppressWarnings("serial") // ignore warning about missing serialVersionUID
public final class LazilyParsedNumber extends Number {
private final String value;

View File

@ -38,6 +38,7 @@ import java.util.Set;
*
* <p>This implementation was derived from Android 4.1's TreeMap class.
*/
@SuppressWarnings("serial") // ignore warning about missing serialVersionUID
public final class LinkedTreeMap<K, V> extends AbstractMap<K, V> implements Serializable {
@SuppressWarnings({ "unchecked", "rawtypes" }) // to avoid Comparable<Comparable<Comparable<...>>>
private static final Comparator<Comparable> NATURAL_ORDER = new Comparator<Comparable>() {
@ -504,10 +505,9 @@ public final class LinkedTreeMap<K, V> extends AbstractMap<K, V> implements Seri
return oldValue;
}
@SuppressWarnings("rawtypes")
@Override public boolean equals(Object o) {
if (o instanceof Entry) {
Entry other = (Entry) o;
Entry<?, ?> other = (Entry<?, ?>) o;
return (key == null ? other.getKey() == null : key.equals(other.getKey()))
&& (value == null ? other.getValue() == null : value.equals(other.getValue()));
}

View File

@ -35,7 +35,6 @@ import java.util.ArrayList;
*/
public final class ArrayTypeAdapter<E> extends TypeAdapter<Object> {
public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() {
@SuppressWarnings({"unchecked", "rawtypes"})
@Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
Type type = typeToken.getType();
if (!(type instanceof GenericArrayType || type instanceof Class && ((Class<?>) type).isArray())) {
@ -44,8 +43,11 @@ public final class ArrayTypeAdapter<E> extends TypeAdapter<Object> {
Type componentType = $Gson$Types.getArrayComponentType(type);
TypeAdapter<?> componentTypeAdapter = gson.getAdapter(TypeToken.get(componentType));
return new ArrayTypeAdapter(
@SuppressWarnings({"unchecked", "rawtypes"})
TypeAdapter<T> arrayAdapter = new ArrayTypeAdapter(
gson, componentTypeAdapter, $Gson$Types.getRawType(componentType));
return arrayAdapter;
}
};
@ -89,7 +91,6 @@ public final class ArrayTypeAdapter<E> extends TypeAdapter<Object> {
}
}
@SuppressWarnings("unchecked")
@Override public void write(JsonWriter out, Object array) throws IOException {
if (array == null) {
out.nullValue();
@ -98,6 +99,7 @@ public final class ArrayTypeAdapter<E> extends TypeAdapter<Object> {
out.beginArray();
for (int i = 0, length = Array.getLength(array); i < length; i++) {
@SuppressWarnings("unchecked")
E value = (E) Array.get(array, i);
componentTypeAdapter.write(out, value);
}

View File

@ -38,7 +38,7 @@ public final class JsonAdapterAnnotationTypeAdapterFactory implements TypeAdapte
this.constructorConstructor = constructorConstructor;
}
@SuppressWarnings("unchecked")
@SuppressWarnings("unchecked") // this is not safe; requires that user has specified correct adapter class for @JsonAdapter
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> targetType) {
Class<? super T> rawType = targetType.getRawType();
@ -49,7 +49,6 @@ public final class JsonAdapterAnnotationTypeAdapterFactory implements TypeAdapte
return (TypeAdapter<T>) getTypeAdapter(constructorConstructor, gson, targetType, annotation);
}
@SuppressWarnings({ "unchecked", "rawtypes" }) // Casts guarded by conditionals.
TypeAdapter<?> getTypeAdapter(ConstructorConstructor constructorConstructor, Gson gson,
TypeToken<?> type, JsonAdapter annotation) {
Object instance = constructorConstructor.get(TypeToken.get(annotation.value())).construct();
@ -62,12 +61,16 @@ public final class JsonAdapterAnnotationTypeAdapterFactory implements TypeAdapte
typeAdapter = ((TypeAdapterFactory) instance).create(gson, type);
} else if (instance instanceof JsonSerializer || instance instanceof JsonDeserializer) {
JsonSerializer<?> serializer = instance instanceof JsonSerializer
? (JsonSerializer) instance
? (JsonSerializer<?>) instance
: null;
JsonDeserializer<?> deserializer = instance instanceof JsonDeserializer
? (JsonDeserializer) instance
? (JsonDeserializer<?>) instance
: null;
typeAdapter = new TreeTypeAdapter(serializer, deserializer, gson, type, null, nullSafe);
@SuppressWarnings({ "unchecked", "rawtypes" })
TypeAdapter<?> tempAdapter = new TreeTypeAdapter(serializer, deserializer, gson, type, null, nullSafe);
typeAdapter = tempAdapter;
nullSafe = false;
} else {
throw new IllegalArgumentException("Invalid attempt to bind an instance of "

View File

@ -166,13 +166,13 @@ public final class ObjectTypeAdapter extends TypeAdapter<Object> {
}
}
@SuppressWarnings("unchecked")
@Override public void write(JsonWriter out, Object value) throws IOException {
if (value == null) {
out.nullValue();
return;
}
@SuppressWarnings("unchecked")
TypeAdapter<Object> typeAdapter = (TypeAdapter<Object>) gson.getAdapter(value.getClass());
if (typeAdapter instanceof ObjectTypeAdapter) {
out.beginObject();

View File

@ -126,19 +126,19 @@ public final class ReflectiveTypeAdapterFactory implements TypeAdapterFactory {
final TypeToken<?> fieldType, boolean serialize, boolean deserialize,
final boolean blockInaccessible) {
final boolean isPrimitive = Primitives.isPrimitive(fieldType.getRawType());
// special casing primitives here saves ~5% on Android...
JsonAdapter annotation = field.getAnnotation(JsonAdapter.class);
TypeAdapter<?> mapped = null;
if (annotation != null) {
// This is not safe; requires that user has specified correct adapter class for @JsonAdapter
mapped = jsonAdapterFactory.getTypeAdapter(
constructorConstructor, context, fieldType, annotation);
}
final boolean jsonAdapterPresent = mapped != null;
if (mapped == null) mapped = context.getAdapter(fieldType);
final TypeAdapter<?> typeAdapter = mapped;
@SuppressWarnings("unchecked")
final TypeAdapter<Object> typeAdapter = (TypeAdapter<Object>) mapped;
return new ReflectiveTypeAdapterFactory.BoundField(name, serialize, deserialize) {
@SuppressWarnings({"unchecked", "rawtypes"}) // the type adapter and field type always agree
@Override void write(JsonWriter writer, Object value)
throws IOException, IllegalAccessException {
if (!serialized) return;
@ -152,8 +152,8 @@ public final class ReflectiveTypeAdapterFactory implements TypeAdapterFactory {
return;
}
writer.name(name);
TypeAdapter t = jsonAdapterPresent ? typeAdapter
: new TypeAdapterRuntimeTypeWrapper(context, typeAdapter, fieldType.getType());
TypeAdapter<Object> t = jsonAdapterPresent ? typeAdapter
: new TypeAdapterRuntimeTypeWrapper<>(context, typeAdapter, fieldType.getType());
t.write(writer, fieldValue);
}
@Override void read(JsonReader reader, Object value)

View File

@ -15,15 +15,14 @@
*/
package com.google.gson.internal.bind;
import java.io.IOException;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
final class TypeAdapterRuntimeTypeWrapper<T> extends TypeAdapter<T> {
private final Gson context;
@ -41,7 +40,6 @@ final class TypeAdapterRuntimeTypeWrapper<T> extends TypeAdapter<T> {
return delegate.read(in);
}
@SuppressWarnings({"rawtypes", "unchecked"})
@Override
public void write(JsonWriter out, T value) throws IOException {
// Order of preference for choosing type adapters
@ -50,10 +48,11 @@ final class TypeAdapterRuntimeTypeWrapper<T> extends TypeAdapter<T> {
// Third preference: reflective type adapter for the runtime type (if it is a sub class of the declared type)
// Fourth preference: reflective type adapter for the declared type
TypeAdapter chosen = delegate;
TypeAdapter<T> chosen = delegate;
Type runtimeType = getRuntimeTypeIfMoreSpecific(type, value);
if (runtimeType != type) {
TypeAdapter runtimeTypeAdapter = context.getAdapter(TypeToken.get(runtimeType));
@SuppressWarnings("unchecked")
TypeAdapter<T> runtimeTypeAdapter = (TypeAdapter<T>) context.getAdapter(TypeToken.get(runtimeType));
if (!(runtimeTypeAdapter instanceof ReflectiveTypeAdapterFactory.Adapter)) {
// The user registered a type adapter for the runtime type, so we will use that
chosen = runtimeTypeAdapter;

View File

@ -891,7 +891,6 @@ public final class TypeAdapters {
}
public static final TypeAdapterFactory ENUM_FACTORY = new TypeAdapterFactory() {
@SuppressWarnings({"rawtypes", "unchecked"})
@Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
Class<? super T> rawType = typeToken.getRawType();
if (!Enum.class.isAssignableFrom(rawType) || rawType == Enum.class) {
@ -900,7 +899,9 @@ public final class TypeAdapters {
if (!rawType.isEnum()) {
rawType = rawType.getSuperclass(); // handle anonymous subclasses
}
return (TypeAdapter<T>) new EnumTypeAdapter(rawType);
@SuppressWarnings({"rawtypes", "unchecked"})
TypeAdapter<T> adapter = (TypeAdapter<T>) new EnumTypeAdapter(rawType);
return adapter;
}
};

View File

@ -466,6 +466,7 @@ public class JsonReader implements Closeable {
}
}
@SuppressWarnings("fallthrough")
int doPeek() throws IOException {
int peekStack = stack[stackSize - 1];
if (peekStack == JsonScope.EMPTY_ARRAY) {
@ -749,6 +750,7 @@ public class JsonReader implements Closeable {
}
}
@SuppressWarnings("fallthrough")
private boolean isLiteral(char c) throws IOException {
switch (c) {
case '/':
@ -1129,6 +1131,7 @@ public class JsonReader implements Closeable {
throw syntaxError("Unterminated string");
}
@SuppressWarnings("fallthrough")
private void skipUnquotedValue() throws IOException {
do {
int i = 0;
@ -1539,6 +1542,7 @@ public class JsonReader implements Closeable {
* @throws NumberFormatException if any unicode escape sequences are
* malformed.
*/
@SuppressWarnings("fallthrough")
private char readEscapeCharacter() throws IOException {
if (pos == limit && !fillBuffer(1)) {
throw syntaxError("Unterminated escape sequence");

View File

@ -153,7 +153,7 @@ public class JsonWriter implements Closeable, Flushable {
static {
REPLACEMENT_CHARS = new String[128];
for (int i = 0; i <= 0x1f; i++) {
REPLACEMENT_CHARS[i] = String.format("\\u%04x", (int) i);
REPLACEMENT_CHARS[i] = String.format("\\u%04x", i);
}
REPLACEMENT_CHARS['"'] = "\\\"";
REPLACEMENT_CHARS['\\'] = "\\\\";

View File

@ -16,9 +16,6 @@
package com.google.gson.common;
import java.lang.reflect.Type;
import java.util.Collection;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
@ -28,6 +25,8 @@ import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.annotations.SerializedName;
import java.lang.reflect.Type;
import java.util.Collection;
/**
* Types used for testing JSON serialization and deserialization
@ -36,7 +35,7 @@ import com.google.gson.annotations.SerializedName;
* @author Joel Leitch
*/
public class TestTypes {
public static class Base {
public static final String BASE_NAME = Base.class.getSimpleName();
public static final String BASE_FIELD_KEY = "baseName";
@ -76,7 +75,7 @@ public class TestTypes {
}
public static class BaseSerializer implements JsonSerializer<Base> {
public static final String NAME = BaseSerializer.class.getSimpleName();
public static final String NAME = BaseSerializer.class.getSimpleName();
@Override
public JsonElement serialize(Base src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject obj = new JsonObject();
@ -85,13 +84,13 @@ public class TestTypes {
}
}
public static class SubSerializer implements JsonSerializer<Sub> {
public static final String NAME = SubSerializer.class.getSimpleName();
public static final String NAME = SubSerializer.class.getSimpleName();
@Override
public JsonElement serialize(Sub src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject obj = new JsonObject();
obj.addProperty(Base.SERIALIZER_KEY, NAME);
return obj;
}
}
}
public static class StringWrapper {
@ -228,6 +227,7 @@ public class TestTypes {
}
}
@SuppressWarnings("overrides") // for missing hashCode() override
public static class ClassWithNoFields {
// Nothing here..
@Override
@ -271,7 +271,7 @@ public class TestTypes {
}
public static class ClassWithTransientFields<T> {
public transient T transientT;
public transient T transientT;
public final transient long transientLongValue;
private final long[] longValue;

View File

@ -141,12 +141,12 @@ public class ArrayTest extends TestCase {
assertEquals("hello", arrayType[0]);
}
@SuppressWarnings("unchecked")
public void testArrayOfCollectionSerialization() throws Exception {
StringBuilder sb = new StringBuilder("[");
int arraySize = 3;
Type typeToSerialize = new TypeToken<Collection<Integer>[]>() {}.getType();
@SuppressWarnings({"rawtypes", "unchecked"})
Collection<Integer>[] arrayOfCollection = new ArrayList[arraySize];
for (int i = 0; i < arraySize; ++i) {
int startValue = (3 * i) + 1;

View File

@ -16,6 +16,16 @@
package com.google.gson.functional;
import static org.junit.Assert.assertArrayEquals;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.common.TestTypes.BagOfPrimitives;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
@ -30,18 +40,7 @@ import java.util.Queue;
import java.util.Set;
import java.util.Stack;
import java.util.Vector;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.common.TestTypes.BagOfPrimitives;
import com.google.gson.reflect.TypeToken;
import junit.framework.TestCase;
import static org.junit.Assert.assertArrayEquals;
/**
* Functional tests for Json serialization and deserialization of collections.
@ -241,35 +240,33 @@ public class CollectionTest extends TestCase {
assertEquals("[1,2,3,4,5,6,7,8,9]", gson.toJson(target));
}
@SuppressWarnings("rawtypes")
public void testRawCollectionSerialization() {
public void testObjectCollectionSerialization() {
BagOfPrimitives bag1 = new BagOfPrimitives();
Collection target = Arrays.asList(bag1, bag1);
Collection<?> target = Arrays.asList(bag1, bag1, "test");
String json = gson.toJson(target);
assertTrue(json.contains(bag1.getExpectedJson()));
}
@SuppressWarnings("rawtypes")
public void testRawCollectionDeserializationNotAlllowed() {
String json = "[0,1,2,3,4,5,6,7,8,9]";
Collection integers = gson.fromJson(json, Collection.class);
Collection<?> integers = gson.fromJson(json, Collection.class);
// JsonReader converts numbers to double by default so we need a floating point comparison
assertEquals(Arrays.asList(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0), integers);
json = "[\"Hello\", \"World\"]";
Collection strings = gson.fromJson(json, Collection.class);
Collection<?> strings = gson.fromJson(json, Collection.class);
assertTrue(strings.contains("Hello"));
assertTrue(strings.contains("World"));
}
@SuppressWarnings({"rawtypes", "unchecked"})
public void testRawCollectionOfBagOfPrimitivesNotAllowed() {
BagOfPrimitives bag = new BagOfPrimitives(10, 20, false, "stringValue");
String json = '[' + bag.getExpectedJson() + ',' + bag.getExpectedJson() + ']';
Collection target = gson.fromJson(json, Collection.class);
Collection<?> target = gson.fromJson(json, Collection.class);
assertEquals(2, target.size());
for (Object bag1 : target) {
// Gson 2.0 converts raw objects into maps
@SuppressWarnings("unchecked")
Map<String, Object> values = (Map<String, Object>) bag1;
assertTrue(values.containsValue(10.0));
assertTrue(values.containsValue(20.0));
@ -324,7 +321,7 @@ public class CollectionTest extends TestCase {
HasArrayListField copy = gson.fromJson("{\"longs\":[1,3]}", HasArrayListField.class);
assertEquals(Arrays.asList(1L, 3L), copy.longs);
}
public void testUserCollectionTypeAdapter() {
Type listOfString = new TypeToken<List<String>>() {}.getType();
Object stringListSerializer = new JsonSerializer<List<String>>() {
@ -343,11 +340,10 @@ public class CollectionTest extends TestCase {
ArrayList<Long> longs = new ArrayList<>();
}
@SuppressWarnings("rawtypes")
private static int[] toIntArray(Collection collection) {
private static int[] toIntArray(Collection<?> collection) {
int[] ints = new int[collection.size()];
int i = 0;
for (Iterator iterator = collection.iterator(); iterator.hasNext(); ++i) {
for (Iterator<?> iterator = collection.iterator(); iterator.hasNext(); ++i) {
Object obj = iterator.next();
if (obj instanceof Integer) {
ints[i] = ((Integer)obj).intValue();

View File

@ -29,15 +29,13 @@ import com.google.gson.JsonSerializer;
import com.google.gson.common.TestTypes.BagOfPrimitives;
import com.google.gson.common.TestTypes.ClassWithCustomTypeConverter;
import com.google.gson.reflect.TypeToken;
import java.util.Date;
import junit.framework.TestCase;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import junit.framework.TestCase;
/**
* Functional tests for the support of custom serializer and deserializers.
@ -220,12 +218,11 @@ public class CustomTypeAdaptersTest extends TestCase {
assertEquals("true", gson.toJson(true, Boolean.class));
}
@SuppressWarnings("rawtypes")
public void testCustomDeserializerInvokedForPrimitives() {
Gson gson = new GsonBuilder()
.registerTypeAdapter(boolean.class, new JsonDeserializer() {
.registerTypeAdapter(boolean.class, new JsonDeserializer<Boolean>() {
@Override
public Object deserialize(JsonElement json, Type t, JsonDeserializationContext context) {
public Boolean deserialize(JsonElement json, Type t, JsonDeserializationContext context) {
return json.getAsInt() != 0;
}
})

View File

@ -54,7 +54,6 @@ import java.util.Set;
import java.util.TimeZone;
import java.util.TreeSet;
import java.util.UUID;
import junit.framework.TestCase;
/**
@ -654,14 +653,13 @@ public class DefaultTypeAdaptersTest extends TestCase {
assertEquals("abc", sb.toString());
}
@SuppressWarnings("rawtypes")
private static class MyClassTypeAdapter extends TypeAdapter<Class> {
private static class MyClassTypeAdapter extends TypeAdapter<Class<?>> {
@Override
public void write(JsonWriter out, Class value) throws IOException {
public void write(JsonWriter out, Class<?> value) throws IOException {
out.value(value.getName());
}
@Override
public Class read(JsonReader in) throws IOException {
public Class<?> read(JsonReader in) throws IOException {
String className = in.nextString();
try {
return Class.forName(className);

View File

@ -22,15 +22,13 @@ import com.google.gson.InstanceCreator;
import com.google.gson.common.TestTypes.Base;
import com.google.gson.common.TestTypes.ClassWithBaseField;
import com.google.gson.common.TestTypes.Sub;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import junit.framework.TestCase;
import java.lang.reflect.Type;
import java.util.SortedSet;
import java.util.TreeSet;
import junit.framework.TestCase;
/**
* Functional Test exercising custom serialization only. When test applies to both
@ -102,13 +100,13 @@ public class InstanceCreatorTest extends TestCase {
assertEquals(SubArrayList.class, list.getClass());
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@SuppressWarnings("unchecked")
public void testInstanceCreatorForParametrizedType() throws Exception {
@SuppressWarnings("serial")
class SubTreeSet<T> extends TreeSet<T> {}
InstanceCreator<SortedSet> sortedSetCreator = new InstanceCreator<SortedSet>() {
@Override public SortedSet createInstance(Type type) {
return new SubTreeSet();
InstanceCreator<SortedSet<?>> sortedSetCreator = new InstanceCreator<SortedSet<?>>() {
@Override public SortedSet<?> createInstance(Type type) {
return new SubTreeSet<>();
}
};
Gson gson = new GsonBuilder()

View File

@ -17,9 +17,8 @@
package com.google.gson.functional;
import com.google.gson.JsonArray;
import junit.framework.TestCase;
import java.math.BigInteger;
import junit.framework.TestCase;
/**
* Functional tests for adding primitives to a JsonArray.

View File

@ -16,18 +16,6 @@
package com.google.gson.functional;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.InstanceCreator;
@ -42,7 +30,17 @@ import com.google.gson.JsonSyntaxException;
import com.google.gson.common.TestTypes;
import com.google.gson.internal.$Gson$Types;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
import junit.framework.TestCase;
/**
@ -78,9 +76,8 @@ public class MapTest extends TestCase {
assertEquals(2, target.get("b").intValue());
}
@SuppressWarnings({"unchecked", "rawtypes"})
public void testRawMapSerialization() {
Map map = new LinkedHashMap();
public void testObjectMapSerialization() {
Map<String, Object> map = new LinkedHashMap<>();
map.put("a", 1);
map.put("b", "string");
String json = gson.toJson(map);
@ -647,7 +644,6 @@ public class MapTest extends TestCase {
}
static final class MapWithGeneralMapParameters {
@SuppressWarnings({"rawtypes", "unchecked"})
final Map<String, Object> map = new LinkedHashMap();
final Map<String, Object> map = new LinkedHashMap<>();
}
}

View File

@ -44,7 +44,6 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import junit.framework.TestCase;
/**
@ -121,18 +120,16 @@ public class ObjectTest extends TestCase {
assertEquals(target.getExpectedJson(), gson.toJson(target));
}
@SuppressWarnings("rawtypes")
public void testClassWithTransientFieldsDeserialization() throws Exception {
String json = "{\"longValue\":[1]}";
ClassWithTransientFields target = gson.fromJson(json, ClassWithTransientFields.class);
ClassWithTransientFields<?> target = gson.fromJson(json, ClassWithTransientFields.class);
assertEquals(json, target.getExpectedJson());
}
@SuppressWarnings("rawtypes")
public void testClassWithTransientFieldsDeserializationTransientFieldsPassedInJsonAreIgnored()
throws Exception {
String json = "{\"transientLongValue\":1,\"longValue\":[1]}";
ClassWithTransientFields target = gson.fromJson(json, ClassWithTransientFields.class);
ClassWithTransientFields<?> target = gson.fromJson(json, ClassWithTransientFields.class);
assertFalse(target.transientLongValue != 1);
}

View File

@ -23,9 +23,6 @@ import com.google.gson.ParameterizedTypeFixtures.MyParameterizedTypeAdapter;
import com.google.gson.ParameterizedTypeFixtures.MyParameterizedTypeInstanceCreator;
import com.google.gson.common.TestTypes.BagOfPrimitives;
import com.google.gson.reflect.TypeToken;
import junit.framework.TestCase;
import java.io.Reader;
import java.io.Serializable;
import java.io.StringReader;
@ -35,6 +32,7 @@ import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import junit.framework.TestCase;
/**
* Functional tests for the serialization and deserialization of parameterized types in Gson.
@ -154,14 +152,19 @@ public class ParameterizedTypesTest extends TestCase {
assertEquals(expected, actual);
}
@SuppressWarnings("unchecked")
@SuppressWarnings("varargs")
@SafeVarargs
private static <T> T[] arrayOf(T... args) {
return args;
}
public void testVariableTypeFieldsAndGenericArraysSerialization() throws Exception {
Integer obj = 0;
Integer[] array = { 1, 2, 3 };
List<Integer> list = new ArrayList<>();
list.add(4);
list.add(5);
List<Integer>[] arrayOfLists = new List[] { list, list };
List<Integer>[] arrayOfLists = arrayOf(list, list);
Type typeOfSrc = new TypeToken<ObjectWithTypeVariables<Integer>>() {}.getType();
ObjectWithTypeVariables<Integer> objToSerialize =
@ -171,14 +174,13 @@ public class ParameterizedTypesTest extends TestCase {
assertEquals(objToSerialize.getExpectedJson(), json);
}
@SuppressWarnings("unchecked")
public void testVariableTypeFieldsAndGenericArraysDeserialization() throws Exception {
Integer obj = 0;
Integer[] array = { 1, 2, 3 };
List<Integer> list = new ArrayList<>();
list.add(4);
list.add(5);
List<Integer>[] arrayOfLists = new List[] { list, list };
List<Integer>[] arrayOfLists = arrayOf(list, list);
Type typeOfSrc = new TypeToken<ObjectWithTypeVariables<Integer>>() {}.getType();
ObjectWithTypeVariables<Integer> objToSerialize =
@ -225,12 +227,11 @@ public class ParameterizedTypesTest extends TestCase {
assertEquals(objAfterDeserialization.getExpectedJson(), json);
}
@SuppressWarnings("unchecked")
public void testParameterizedTypeGenericArraysSerialization() throws Exception {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
List<Integer>[] arrayOfLists = new List[] { list, list };
List<Integer>[] arrayOfLists = arrayOf(list, list);
Type typeOfSrc = new TypeToken<ObjectWithTypeVariables<Integer>>() {}.getType();
ObjectWithTypeVariables<Integer> objToSerialize =
@ -239,12 +240,11 @@ public class ParameterizedTypesTest extends TestCase {
assertEquals("{\"arrayOfListOfTypeParameters\":[[1,2],[1,2]]}", json);
}
@SuppressWarnings("unchecked")
public void testParameterizedTypeGenericArraysDeserialization() throws Exception {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
List<Integer>[] arrayOfLists = new List[] { list, list };
List<Integer>[] arrayOfLists = arrayOf(list, list);
Type typeOfSrc = new TypeToken<ObjectWithTypeVariables<Integer>>() {}.getType();
ObjectWithTypeVariables<Integer> objToSerialize =
@ -459,7 +459,7 @@ public class ParameterizedTypesTest extends TestCase {
return true;
}
}
// Begin: tests to reproduce issue 103
private static class Quantity {
@SuppressWarnings("unused")
@ -475,21 +475,21 @@ public class ParameterizedTypesTest extends TestCase {
}
private interface Immutable {
}
public static final class Amount<Q extends Quantity>
public static final class Amount<Q extends Quantity>
implements Measurable<Q>, Field<Amount<?>>, Serializable, Immutable {
private static final long serialVersionUID = -7560491093120970437L;
int value = 30;
}
public void testDeepParameterizedTypeSerialization() {
Amount<MyQuantity> amount = new Amount<>();
String json = gson.toJson(amount);
assertTrue(json.contains("value"));
assertTrue(json.contains("30"));
}
public void testDeepParameterizedTypeDeserialization() {
String json = "{value:30}";
Type type = new TypeToken<Amount<MyQuantity>>() {}.getType();

View File

@ -23,11 +23,9 @@ import com.google.gson.common.TestTypes.BagOfPrimitives;
import com.google.gson.common.TestTypes.ClassWithTransientFields;
import com.google.gson.common.TestTypes.Nested;
import com.google.gson.common.TestTypes.PrimitiveArray;
import junit.framework.TestCase;
import java.util.ArrayList;
import java.util.List;
import junit.framework.TestCase;
/**
* Functional tests for print formatting.
@ -45,13 +43,12 @@ public class PrintFormattingTest extends TestCase {
gson = new Gson();
}
@SuppressWarnings({"unchecked", "rawtypes"})
public void testCompactFormattingLeavesNoWhiteSpace() {
List list = new ArrayList();
List<Object> list = new ArrayList<>();
list.add(new BagOfPrimitives());
list.add(new Nested());
list.add(new PrimitiveArray());
list.add(new ClassWithTransientFields());
list.add(new ClassWithTransientFields<>());
String json = gson.toJson(list);
assertContainsNoWhiteSpace(json);

View File

@ -16,14 +16,6 @@
package com.google.gson.functional;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import junit.framework.TestCase;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
@ -34,6 +26,12 @@ import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import junit.framework.TestCase;
/**
* Collection of functional tests for DOM tree based type adapters.
@ -44,7 +42,7 @@ public class TreeTypeAdaptersTest extends TestCase {
private static final Student STUDENT1 = new Student(STUDENT1_ID, "first");
private static final Student STUDENT2 = new Student(STUDENT2_ID, "second");
private static final Type TYPE_COURSE_HISTORY =
new TypeToken<Course<HistoryCourse>>(){}.getType();
new TypeToken<Course<HistoryCourse>>(){}.getType();
private static final Id<Course<HistoryCourse>> COURSE_ID =
new Id<>("10", TYPE_COURSE_HISTORY);
@ -93,7 +91,6 @@ public class TreeTypeAdaptersTest extends TestCase {
private static final class IdTreeTypeAdapter implements JsonSerializer<Id<?>>,
JsonDeserializer<Id<?>> {
@SuppressWarnings("rawtypes")
@Override
public Id<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
@ -104,7 +101,7 @@ public class TreeTypeAdaptersTest extends TestCase {
// Since Id takes only one TypeVariable, the actual type corresponding to the first
// TypeVariable is the Type we are looking for
Type typeOfId = parameterizedType.getActualTypeArguments()[0];
return new Id(json.getAsString(), typeOfId);
return new Id<>(json.getAsString(), typeOfId);
}
@Override

View File

@ -16,16 +16,14 @@
package com.google.gson.functional;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.Arrays;
import junit.framework.TestCase;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import junit.framework.TestCase;
/**
* Functional test for Gson serialization and deserialization of
@ -70,6 +68,7 @@ public class TypeVariableTest extends TestCase {
assertEquals(blue1, blue2);
}
@SuppressWarnings("overrides") // for missing hashCode() override
public static class Blue extends Red<Boolean> {
public Blue() {
super(false);
@ -79,7 +78,6 @@ public class TypeVariableTest extends TestCase {
super(value);
}
// Technically, we should implement hashcode too
@Override
public boolean equals(Object o) {
if (!(o instanceof Blue)) {
@ -100,6 +98,7 @@ public class TypeVariableTest extends TestCase {
}
}
@SuppressWarnings("overrides") // for missing hashCode() override
public static class Foo<S, T> extends Red<Boolean> {
private S someSField;
private T someTField;
@ -113,7 +112,6 @@ public class TypeVariableTest extends TestCase {
this.someTField = tValue;
}
// Technically, we should implement hashcode too
@Override
@SuppressWarnings("unchecked")
public boolean equals(Object o) {

View File

@ -15,7 +15,8 @@
*/
package com.google.gson.internal;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
@ -29,7 +30,7 @@ public class JavaVersionTest {
@Test
public void testGetMajorJavaVersion() {
JavaVersion.getMajorJavaVersion();
assertTrue(JavaVersion.getMajorJavaVersion() >= 7); // Gson currently requires at least Java 7
}
@Test

View File

@ -213,6 +213,7 @@ public final class LinkedTreeMapTest extends TestCase {
assertEquals(Collections.singletonMap("a", 1), deserialized);
}
@SuppressWarnings("varargs")
@SafeVarargs
private final <T> void assertIterationOrder(Iterable<T> actual, T... expected) {
ArrayList<T> actualList = new ArrayList<>();

View File

@ -69,6 +69,14 @@
<version>3.10.1</version>
<configuration>
<release>${javaVersion}</release>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
<failOnWarning>true</failOnWarning>
<compilerArgs>
<!-- Enable all warnings, except for ones which cause issues when building with newer JDKs, see also
https://docs.oracle.com/en/java/javase/11/tools/javac.html -->
<compilerArg>-Xlint:all,-options</compilerArg>
</compilerArgs>
<jdkToolchain>
<version>[11,)</version>
</jdkToolchain>