diff --git a/gson/gson/src/main/java/com/google/gson/internal/ConstructorConstructor.java b/gson/gson/src/main/java/com/google/gson/internal/ConstructorConstructor.java index fc4ff7d617708b14cff6e59e1d83ff63e51837e3..f5bd9ac37ab8f4d5dd87fefd267a12f041bf07c4 100644 --- a/gson/gson/src/main/java/com/google/gson/internal/ConstructorConstructor.java +++ b/gson/gson/src/main/java/com/google/gson/internal/ConstructorConstructor.java @@ -14,7 +14,6 @@ * limitations under the License. */ - package com.google.gson.internal; import com.google.gson.InstanceCreator; @@ -54,9 +53,9 @@ public final class ConstructorConstructor { private final List<ReflectionAccessFilter> reflectionFilters; public ConstructorConstructor( - Map<Type, InstanceCreator<?>> instanceCreators, - boolean useJdkUnsafe, - List<ReflectionAccessFilter> reflectionFilters) { + Map<Type, InstanceCreator<?>> instanceCreators, + boolean useJdkUnsafe, + List<ReflectionAccessFilter> reflectionFilters) { this.instanceCreators = instanceCreators; this.useJdkUnsafe = useJdkUnsafe; this.reflectionFilters = reflectionFilters; @@ -66,15 +65,15 @@ public final class ConstructorConstructor { int modifiers = c.getModifiers(); if (Modifier.isInterface(modifiers)) { return "Interfaces can't be instantiated! Register an InstanceCreator" - + " or a TypeAdapter for this type. Interface name: " - + c.getName(); + + " or a TypeAdapter for this type. Interface name: " + + c.getName(); } if (Modifier.isAbstract(modifiers)) { return "Abstract classes can't be instantiated! Adjust the R8 configuration or register" - + " an InstanceCreator or a TypeAdapter for this type. Class name: " - + c.getName() - + "\nSee " - + TroubleshootingGuide.createUrl("r8-abstract-class"); + + " an InstanceCreator or a TypeAdapter for this type. Class name: " + + c.getName() + + "\nSee " + + TroubleshootingGuide.createUrl("r8-abstract-class"); } return null; } @@ -106,7 +105,7 @@ public final class ConstructorConstructor { } FilterResult filterResult = - ReflectionAccessFilterHelper.getFilterResult(reflectionFilters, rawType); + ReflectionAccessFilterHelper.getFilterResult(reflectionFilters, rawType); ObjectConstructor<T> defaultConstructor = newDefaultConstructor(rawType, filterResult); if (defaultConstructor != null) { return defaultConstructor; @@ -136,11 +135,11 @@ public final class ConstructorConstructor { return newUnsafeAllocator(rawType); } else { final String message = - "Unable to create instance of " - + rawType - + "; ReflectionAccessFilter does not permit using reflection or Unsafe. Register an" - + " InstanceCreator or a TypeAdapter for this type or adjust the access filter to" - + " allow using reflection."; + "Unable to create instance of " + + rawType + + "; ReflectionAccessFilter does not permit using reflection or Unsafe. Register an" + + " InstanceCreator or a TypeAdapter for this type or adjust the access filter to" + + " allow using reflection."; return new ObjectConstructor<T>() { @Override public T construct() { @@ -164,13 +163,12 @@ public final class ConstructorConstructor { return null; } - /** * Creates constructors for special JDK collection types which do not have a public no-args * constructor. */ private static <T> ObjectConstructor<T> newSpecialCollectionConstructor( - final Type type, Class<? super T> rawType) { + final Type type, Class<? super T> rawType) { if (EnumSet.class.isAssignableFrom(rawType)) { return new ObjectConstructor<T>() { @Override @@ -216,7 +214,7 @@ public final class ConstructorConstructor { } private static <T> ObjectConstructor<T> newDefaultConstructor( - Class<? super T> rawType, FilterResult filterResult) { + Class<? super T> rawType, FilterResult filterResult) { // Cannot invoke constructor of abstract class if (Modifier.isAbstract(rawType.getModifiers())) { return null; @@ -230,21 +228,21 @@ public final class ConstructorConstructor { } boolean canAccess = - filterResult == FilterResult.ALLOW - || (ReflectionAccessFilterHelper.canAccess(constructor, null) - // Be a bit more lenient here for BLOCK_ALL; if constructor is accessible and public - // then allow calling it - && (filterResult != FilterResult.BLOCK_ALL + filterResult == FilterResult.ALLOW + || (ReflectionAccessFilterHelper.canAccess(constructor, null) + // Be a bit more lenient here for BLOCK_ALL; if constructor is accessible and public + // then allow calling it + && (filterResult != FilterResult.BLOCK_ALL || Modifier.isPublic(constructor.getModifiers()))); if (!canAccess) { final String message = - "Unable to invoke no-args constructor of " - + rawType - + ";" - + " constructor is not accessible and ReflectionAccessFilter does not permit making" - + " it accessible. Register an InstanceCreator or a TypeAdapter for this type, change" - + " the visibility of the constructor or adjust the access filter."; + "Unable to invoke no-args constructor of " + + rawType + + ";" + + " constructor is not accessible and ReflectionAccessFilter does not permit making" + + " it accessible. Register an InstanceCreator or a TypeAdapter for this type, change" + + " the visibility of the constructor or adjust the access filter."; return new ObjectConstructor<T>() { @Override public T construct() { @@ -290,18 +288,18 @@ public final class ConstructorConstructor { // sure that class is not abstract catch (InstantiationException e) { throw new RuntimeException( - "Failed to invoke constructor '" - + ReflectionHelper.constructorToString(constructor) - + "' with no args", - e); + "Failed to invoke constructor '" + + ReflectionHelper.constructorToString(constructor) + + "' with no args", + e); } catch (InvocationTargetException e) { // TODO: don't wrap if cause is unchecked? // TODO: JsonParseException ? throw new RuntimeException( - "Failed to invoke constructor '" - + ReflectionHelper.constructorToString(constructor) - + "' with no args", - e.getCause()); + "Failed to invoke constructor '" + + ReflectionHelper.constructorToString(constructor) + + "' with no args", + e.getCause()); } catch (IllegalAccessException e) { throw ReflectionHelper.createExceptionForUnexpectedIllegalAccess(e); } @@ -312,7 +310,7 @@ public final class ConstructorConstructor { /** Constructors for common interface types like Map and List and their subtypes. */ @SuppressWarnings("unchecked") // use runtime checks to guarantee that 'T' is what it is private static <T> ObjectConstructor<T> newDefaultImplementationConstructor( - final Type type, Class<? super T> rawType) { + final Type type, Class<? super T> rawType) { /* * IMPORTANT: Must only create instances for classes with public no-args constructor. @@ -377,7 +375,7 @@ public final class ConstructorConstructor { } }; } else if (type instanceof ParameterizedType - && !String.class.isAssignableFrom( + && !String.class.isAssignableFrom( TypeToken.get(((ParameterizedType) type).getActualTypeArguments()[0]).getRawType())) { return new ObjectConstructor<T>() { @Override @@ -409,28 +407,28 @@ public final class ConstructorConstructor { return newInstance; } catch (Exception e) { throw new RuntimeException( - ("Unable to create instance of " - + rawType - + ". Registering an InstanceCreator or a TypeAdapter for this type, or adding a" - + " no-args constructor may fix this problem."), - e); + ("Unable to create instance of " + + rawType + + ". Registering an InstanceCreator or a TypeAdapter for this type, or adding a" + + " no-args constructor may fix this problem."), + e); } } }; } else { String exceptionMessage = - "Unable to create instance of " - + rawType - + "; usage of JDK Unsafe is disabled. Registering an InstanceCreator or a TypeAdapter" - + " for this type, adding a no-args constructor, or enabling usage of JDK Unsafe may" - + " fix this problem."; + "Unable to create instance of " + + rawType + + "; usage of JDK Unsafe is disabled. Registering an InstanceCreator or a TypeAdapter" + + " for this type, adding a no-args constructor, or enabling usage of JDK Unsafe may" + + " fix this problem."; // Check if R8 removed all constructors if (rawType.getDeclaredConstructors().length == 0) { // R8 with Unsafe disabled might not be common enough to warrant a separate Troubleshooting // Guide entry exceptionMessage += - " Or adjust your R8 configuration to keep the no-args constructor of the class."; + " Or adjust your R8 configuration to keep the no-args constructor of the class."; } // Explicit final variable to allow usage in the anonymous class below @@ -449,5 +447,4 @@ public final class ConstructorConstructor { public String toString() { return instanceCreators.toString(); } - } diff --git a/gson/gson/src/main/java/com/google/gson/internal/reflect/ReflectionHelper.java b/gson/gson/src/main/java/com/google/gson/internal/reflect/ReflectionHelper.java index 5dd127d4bb96ff71d3db2e64547685465361827d..7ee75bde92a4d63f83b5ffbb002daa3170228630 100644 --- a/gson/gson/src/main/java/com/google/gson/internal/reflect/ReflectionHelper.java +++ b/gson/gson/src/main/java/com/google/gson/internal/reflect/ReflectionHelper.java @@ -1,4 +1,3 @@ - /* * Copyright (C) 2021 Google Inc. * @@ -49,9 +48,9 @@ public class ReflectionHelper { if (e.getClass().getName().equals("java.lang.reflect.InaccessibleObjectException")) { String message = e.getMessage(); String troubleshootingId = - message != null && message.contains("to module com.google.gson") - ? "reflection-inaccessible-to-module-gson" - : "reflection-inaccessible"; + message != null && message.contains("to module com.google.gson") + ? "reflection-inaccessible-to-module-gson" + : "reflection-inaccessible"; return "\nSee " + TroubleshootingGuide.createUrl(troubleshootingId); } return ""; @@ -70,12 +69,12 @@ public class ReflectionHelper { } catch (Exception exception) { String description = getAccessibleObjectDescription(object, false); throw new JsonIOException( - "Failed making " - + description - + " accessible; either increase its visibility" - + " or write a custom TypeAdapter for its declaring type." - + getInaccessibleTroubleshootingSuffix(exception), - exception); + "Failed making " + + description + + " accessible; either increase its visibility" + + " or write a custom TypeAdapter for its declaring type." + + getInaccessibleTroubleshootingSuffix(exception), + exception); } } @@ -88,7 +87,7 @@ public class ReflectionHelper { * @param uppercaseFirstLetter whether the first letter of the description should be uppercased */ public static String getAccessibleObjectDescription( - AccessibleObject object, boolean uppercaseFirstLetter) { + AccessibleObject object, boolean uppercaseFirstLetter) { String description; if (object instanceof Field) { @@ -131,13 +130,13 @@ public class ReflectionHelper { // Ideally parameter type would be java.lang.reflect.Executable, but that was added in Java 8 private static void appendExecutableParameters( - AccessibleObject executable, StringBuilder stringBuilder) { + AccessibleObject executable, StringBuilder stringBuilder) { stringBuilder.append('('); Class<?>[] parameters = - (executable instanceof Method) - ? ((Method) executable).getParameterTypes() - : ((Constructor<?>) executable).getParameterTypes(); + (executable instanceof Method) + ? ((Method) executable).getParameterTypes() + : ((Constructor<?>) executable).getParameterTypes(); for (int i = 0; i < parameters.length; i++) { if (i > 0) { stringBuilder.append(", "); @@ -169,12 +168,12 @@ public class ReflectionHelper { return null; } catch (Exception exception) { return "Failed making constructor '" - + constructorToString(constructor) - + "' accessible; either increase its visibility or write a custom InstanceCreator or" - + " TypeAdapter for its declaring type: " - // Include the message since it might contain more detailed information - + exception.getMessage() - + getInaccessibleTroubleshootingSuffix(exception); + + constructorToString(constructor) + + "' accessible; either increase its visibility or write a custom InstanceCreator or" + + " TypeAdapter for its declaring type: " + // Include the message since it might contain more detailed information + + exception.getMessage() + + getInaccessibleTroubleshootingSuffix(exception); } } @@ -197,26 +196,26 @@ public class ReflectionHelper { } public static RuntimeException createExceptionForUnexpectedIllegalAccess( - IllegalAccessException exception) { + IllegalAccessException exception) { throw new RuntimeException( - "Unexpected IllegalAccessException occurred (Gson " - + GsonBuildConfig.VERSION - + "). Certain ReflectionAccessFilter features require Java >= 9 to work correctly. If" - + " you are not using ReflectionAccessFilter, report this to the Gson maintainers.", - exception); + "Unexpected IllegalAccessException occurred (Gson " + + GsonBuildConfig.VERSION + + "). Certain ReflectionAccessFilter features require Java >= 9 to work correctly. If" + + " you are not using ReflectionAccessFilter, report this to the Gson maintainers.", + exception); } private static RuntimeException createExceptionForRecordReflectionException( - ReflectiveOperationException exception) { + ReflectiveOperationException exception) { throw new RuntimeException( - "Unexpected ReflectiveOperationException occurred" - + " (Gson " - + GsonBuildConfig.VERSION - + ")." - + " To support Java records, reflection is utilized to read out information" - + " about records. All these invocations happens after it is established" - + " that records exist in the JVM. This exception is unexpected behavior.", - exception); + "Unexpected ReflectiveOperationException occurred" + + " (Gson " + + GsonBuildConfig.VERSION + + ")." + + " To support Java records, reflection is utilized to read out information" + + " about records. All these invocations happens after it is established" + + " that records exist in the JVM. This exception is unexpected behavior.", + exception); } /** Internal abstraction over reflection when Records are supported. */ @@ -307,19 +306,19 @@ public class ReflectionHelper { @Override String[] getRecordComponentNames(Class<?> clazz) { throw new UnsupportedOperationException( - "Records are not supported on this JVM, this method should not be called"); + "Records are not supported on this JVM, this method should not be called"); } @Override <T> Constructor<T> getCanonicalRecordConstructor(Class<T> raw) { throw new UnsupportedOperationException( - "Records are not supported on this JVM, this method should not be called"); + "Records are not supported on this JVM, this method should not be called"); } @Override public Method getAccessor(Class<?> raw, Field field) { throw new UnsupportedOperationException( - "Records are not supported on this JVM, this method should not be called"); + "Records are not supported on this JVM, this method should not be called"); } } } diff --git a/gson/gson/src/test/java/com/google/gson/JsonObjectAsMapTest.java b/gson/gson/src/test/java/com/google/gson/JsonObjectAsMapTest.java index af4ad927f2e419c86e29c80d596184ec82858532..0e8187a3776020fa4e4107ca12cfa7d95696063e 100644 --- a/gson/gson/src/test/java/com/google/gson/JsonObjectAsMapTest.java +++ b/gson/gson/src/test/java/com/google/gson/JsonObjectAsMapTest.java @@ -192,7 +192,7 @@ public class JsonObjectAsMapTest { assertThat(keySet).containsExactly("b", "a").inOrder(); // Key set doesn't support insertions - assertThrows(UnsupportedOperationException.class, ()-> keySet.add("c")); + assertThrows(UnsupportedOperationException.class, () -> keySet.add("c")); assertThat(keySet.remove("a")).isTrue(); assertThat(map.keySet()).isEqualTo(Collections.singleton("b")); diff --git a/gson/metrics/src/main/java/com/google/gson/metrics/BagOfPrimitivesDeserializationBenchmark.java b/gson/metrics/src/main/java/com/google/gson/metrics/BagOfPrimitivesDeserializationBenchmark.java index 85382fc3fb28953c1d7390ae9321edfcfaa27e66..0f30b7b7eea16717c653b51cf35198aa9b516fd8 100644 --- a/gson/metrics/src/main/java/com/google/gson/metrics/BagOfPrimitivesDeserializationBenchmark.java +++ b/gson/metrics/src/main/java/com/google/gson/metrics/BagOfPrimitivesDeserializationBenchmark.java @@ -61,6 +61,4 @@ public class BagOfPrimitivesDeserializationBenchmark { UtilDeserialisationJson.deserialiserObjet(jr, BagOfPrimitives.class); } } - - -} \ No newline at end of file +} diff --git a/gson/metrics/src/main/java/com/google/gson/metrics/CollectionsDeserializationBenchmark.java b/gson/metrics/src/main/java/com/google/gson/metrics/CollectionsDeserializationBenchmark.java index caacfa6b839a914b1d4eaded7af70d6f5f79ddf4..65a5701afc7adafc1949f13f71a7e1232e50822a 100644 --- a/gson/metrics/src/main/java/com/google/gson/metrics/CollectionsDeserializationBenchmark.java +++ b/gson/metrics/src/main/java/com/google/gson/metrics/CollectionsDeserializationBenchmark.java @@ -33,7 +33,7 @@ import java.util.List; public class CollectionsDeserializationBenchmark { private static final TypeToken<List<BagOfPrimitives>> LIST_TYPE_TOKEN = - new TypeToken<List<BagOfPrimitives>>() {}; + new TypeToken<List<BagOfPrimitives>>() {}; private static final Type LIST_TYPE = LIST_TYPE_TOKEN.getType(); private Gson gson; private String json; @@ -105,6 +105,4 @@ public class CollectionsDeserializationBenchmark { UtilDeserialisationJson.deserialiserListe(json, BagOfPrimitives.class); } } - - -} \ No newline at end of file +} diff --git a/gson/metrics/src/main/java/com/google/gson/metrics/UtilDeserialisationJson.java b/gson/metrics/src/main/java/com/google/gson/metrics/UtilDeserialisationJson.java index 5c5502438e872b3908db5a5fec807381301abdd5..f6cb40dba3ea6a8d0e5c523a0202c08e23252f1b 100644 --- a/gson/metrics/src/main/java/com/google/gson/metrics/UtilDeserialisationJson.java +++ b/gson/metrics/src/main/java/com/google/gson/metrics/UtilDeserialisationJson.java @@ -8,61 +8,61 @@ import java.util.List; public class UtilDeserialisationJson { - private UtilDeserialisationJson() { - throw new AssertionError("La classe UtilDeserialisationJson ne doit pas être instanciée."); - } + private UtilDeserialisationJson() { + throw new AssertionError("La classe UtilDeserialisationJson ne doit pas être instanciée."); + } - // Désérialise une liste d'objets de type T à partir d'une chaîne JSON. - public static <T> List<T> deserialiserListe(String json, Class<T> clazz) throws Exception { - JsonReader jr = new JsonReader(new StringReader(json)); - List<T> resultat = new ArrayList<>(); - jr.beginArray(); - while (jr.hasNext()) { - resultat.add(deserialiserObjet(jr, clazz)); - } - jr.endArray(); - return resultat; + // Désérialise une liste d'objets de type T à partir d'une chaîne JSON. + public static <T> List<T> deserialiserListe(String json, Class<T> clazz) throws Exception { + JsonReader jr = new JsonReader(new StringReader(json)); + List<T> resultat = new ArrayList<>(); + jr.beginArray(); + while (jr.hasNext()) { + resultat.add(deserialiserObjet(jr, clazz)); } + jr.endArray(); + return resultat; + } - // Désérialise un objet de type T à partir d'un JsonReader. - public static <T> T deserialiserObjet(JsonReader jr, Class<T> clazz) throws Exception { - T objet = clazz.getDeclaredConstructor().newInstance(); - jr.beginObject(); - while (jr.hasNext()) { - String name = jr.nextName(); - Field champ = chercherChamp(clazz, name); - if (champ != null) { - affecterChamp(jr, objet, champ); - } - } - jr.endObject(); - return objet; + // Désérialise un objet de type T à partir d'un JsonReader. + public static <T> T deserialiserObjet(JsonReader jr, Class<T> clazz) throws Exception { + T objet = clazz.getDeclaredConstructor().newInstance(); + jr.beginObject(); + while (jr.hasNext()) { + String name = jr.nextName(); + Field champ = chercherChamp(clazz, name); + if (champ != null) { + affecterChamp(jr, objet, champ); + } } + jr.endObject(); + return objet; + } - // Cherche le champ correspondant dans la classe spécifiée par son nom. - private static Field chercherChamp(Class<?> clazz, String nomChamp) { - for (Field champ : clazz.getDeclaredFields()) { - if (champ.getName().equals(nomChamp)) { - return champ; - } - } - return null; + // Cherche le champ correspondant dans la classe spécifiée par son nom. + private static Field chercherChamp(Class<?> clazz, String nomChamp) { + for (Field champ : clazz.getDeclaredFields()) { + if (champ.getName().equals(nomChamp)) { + return champ; + } } + return null; + } - // Affecte la valeur lue depuis le JsonReader au champ de l'objet. - private static void affecterChamp(JsonReader jr, Object objet, Field champ) throws Exception { - Class<?> typeChamp = champ.getType(); - champ.setAccessible(true); // Pour accéder aux champs privés - if (typeChamp.equals(long.class)) { - champ.setLong(objet, jr.nextLong()); - } else if (typeChamp.equals(int.class)) { - champ.setInt(objet, jr.nextInt()); - } else if (typeChamp.equals(boolean.class)) { - champ.setBoolean(objet, jr.nextBoolean()); - } else if (typeChamp.equals(String.class)) { - champ.set(objet, jr.nextString()); - } else { - throw new RuntimeException("Type inattendu: " + typeChamp + ", nom: " + champ.getName()); - } + // Affecte la valeur lue depuis le JsonReader au champ de l'objet. + private static void affecterChamp(JsonReader jr, Object objet, Field champ) throws Exception { + Class<?> typeChamp = champ.getType(); + champ.setAccessible(true); // Pour accéder aux champs privés + if (typeChamp.equals(long.class)) { + champ.setLong(objet, jr.nextLong()); + } else if (typeChamp.equals(int.class)) { + champ.setInt(objet, jr.nextInt()); + } else if (typeChamp.equals(boolean.class)) { + champ.setBoolean(objet, jr.nextBoolean()); + } else if (typeChamp.equals(String.class)) { + champ.set(objet, jr.nextString()); + } else { + throw new RuntimeException("Type inattendu: " + typeChamp + ", nom: " + champ.getName()); } -} \ No newline at end of file + } +}