Refactored exclusion strategies so that they can easily be exposed as part of the public API.

This commit is contained in:
Joel Leitch 2009-10-07 09:23:14 +00:00
parent c892738fbb
commit 839b0c2f94
23 changed files with 481 additions and 182 deletions

View File

@ -16,7 +16,6 @@
package com.google.gson;
import java.lang.reflect.Field;
/**
* Strategy for excluding anonymous and local classes.
@ -25,8 +24,8 @@ import java.lang.reflect.Field;
*/
final class AnonymousAndLocalClassExclusionStrategy implements ExclusionStrategy {
public boolean shouldSkipField(Field f) {
return isAnonymousOrLocal(f.getType());
public boolean shouldSkipField(FieldAttributes f) {
return isAnonymousOrLocal(f.getDeclaredClass());
}
public boolean shouldSkipClass(Class<?> clazz) {

View File

@ -16,7 +16,6 @@
package com.google.gson;
import java.lang.reflect.Field;
import java.util.Collection;
/**
@ -33,7 +32,7 @@ final class DisjunctionExclusionStrategy implements ExclusionStrategy {
this.strategies = strategies;
}
public boolean shouldSkipField(Field f) {
public boolean shouldSkipField(FieldAttributes f) {
for (ExclusionStrategy strategy : strategies) {
if (strategy.shouldSkipField(f)) {
return true;

View File

@ -16,31 +16,55 @@
package com.google.gson;
import java.lang.reflect.Field;
/**
* A strategy definition that is used by the {@link ObjectNavigator} to
* determine whether or not the field of the object should be ignored during
* navigation.
* A strategy pattern (see "Design Patterns" written by GoF for some literature on this pattern)
* definition that is used to decide whether or not a field or top-level class should be serialized
* (or deserialized) as part of the JSON output/input.
*
* As well, for now this class is also responsible for excluding entire
* classes. This is somewhat a mixing of concerns for this object, but
* it will suffice for now. We can always break it down into two
* different strategies later.
* <p>The following example show an implementation of an {@code ExclusionStrategy} where a specific
* type will be excluded from the output.
*
* <p><pre class="code">
* private static class UserDefinedExclusionStrategy implements ExclusionStrategy {
* private final Class&lt;?&gt; excludedThisClass;
*
* UserDefinedExclusionStrategy(Class&lt;?&gt; excludedThisClass) {
* this.excludedThisClass = excludedThisClass;
* }
*
* public boolean shouldSkipClass(Class&lt;?&gt; clazz) {
* return excludedThisClass.equals(clazz);
* }
*
* public boolean shouldSkipField(FieldAttributes f) {
* return excludedThisClass.equals(f.getDeclaredClass());
* }
* }
*
* ExclusionStrategy excludeStrings = new UserDefinedExclusionStrategy(String.class);
* Gson gson = new GsonBuilder()
* .setExclusionStrategies(excludeStrings)
* .create();
* </pre>
*
* @author Inderjeet Singh
* @author Joel Leitch
*
* @see GsonBuilder#setExclusionStrategies(ExclusionStrategy...)
*
* @since 1.4
*/
interface ExclusionStrategy {
/**
* @param f the field object that is under test
* @return true if the field should be ignored otherwise false
* @return true if the field should be ignored; otherwise false
*/
public boolean shouldSkipField(Field f);
public boolean shouldSkipField(FieldAttributes f);
/**
* @param clazz the class object that is under test
* @return true if the class should be ignored otherwise false
* @return true if the class should be ignored; otherwise false
*/
public boolean shouldSkipClass(Class<?> clazz);
}

View File

@ -15,8 +15,6 @@
*/
package com.google.gson;
import java.lang.reflect.Field;
import com.google.gson.annotations.Expose;
/**
@ -31,7 +29,7 @@ final class ExposeAnnotationDeserializationExclusionStrategy implements Exclusio
return false;
}
public boolean shouldSkipField(Field f) {
public boolean shouldSkipField(FieldAttributes f) {
Expose annotation = f.getAnnotation(Expose.class);
if (annotation == null) {
return true;

View File

@ -18,8 +18,6 @@ package com.google.gson;
import com.google.gson.annotations.Expose;
import java.lang.reflect.Field;
/**
* Excludes fields that do not have the {@link Expose} annotation
*
@ -32,7 +30,7 @@ final class ExposeAnnotationSerializationExclusionStrategy implements ExclusionS
return false;
}
public boolean shouldSkipField(Field f) {
public boolean shouldSkipField(FieldAttributes f) {
Expose annotation = f.getAnnotation(Expose.class);
if (annotation == null) {
return true;

View File

@ -0,0 +1,124 @@
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
/**
* A data object that stores attributes of a field.
*
* <p>This class is immutable; therefore, it can be safely shared across threads.
*
* @author Inderjeet Singh
* @author Joel Leitch
*
* @since 1.4
*/
final class FieldAttributes {
private final Field field;
/**
* Constructs a Field Attributes object
* @param f
*/
FieldAttributes(Field f) {
Preconditions.checkNotNull(f);
field = f;
}
/**
* @return the name of the field
*/
public String getName() {
return field.getName();
}
/**
* <p>For example, assume the following class definition:
* <pre class="code">
* public class Foo {
* private String bar;
* private List&lt;String&gt; red;
* }
*
* Type listParmeterizedType = new TypeToken<List<String>>() {}.getType();
* </pre>
*
* <p>This method would return {@code String.class} for the {@code bar} field and
* {@code listParameterizedType} for the {@code red} field.
*
* @return the specific type declared for this field
*/
public Type getDeclaredType() {
return field.getGenericType();
}
/**
* Returns the {@code Class<?>} object that was declared for this field.
*
* <p>For example, assume the following class definition:
* <pre class="code">
* public class Foo {
* private String bar;
* private List&lt;String&gt; red;
* }
* </pre>
*
* <p>This method would return {@code String.class} for the {@code bar} field and
* {@code List.class} for the {@code red} field.
*
* @return the specific class object that was declared for the field
*/
public Class<?> getDeclaredClass() {
return field.getType();
}
/**
* Return the {@link T} annotation object from this field if it exist; otherwise returns
* {@code null}.
*
* @param annotation the class of the annotation that will be retrieved
* @return the annotation instance if it is bound to the field; otherwise {@code null}
*/
public <T extends Annotation> T getAnnotation(Class<T> annotation) {
return field.getAnnotation(annotation);
}
/**
* Returns {@code true} if the field is defined with the {@code modifier}.
*
* <p>This method is meant to be called as:
* <pre class="code">
* boolean hasPublicModifier = fieldAttribute.hasModifier(java.lang.reflect.Modifier.PUBLIC);
* </pre>
*
* @see java.lang.reflect.Modifier
*/
public boolean hasModifier(int modifier) {
return (field.getModifiers() & modifier) != 0;
}
/**
* This is exposed internally only for the
* @return
*/
boolean isSynthetic() {
return field.isSynthetic();
}
}

View File

@ -79,12 +79,19 @@ public final class Gson {
static final boolean DEFAULT_JSON_NON_EXECUTABLE = false;
// Default instances of plug-ins
static final AnonymousAndLocalClassExclusionStrategy DEFAULT_ANON_LOCAL_CLASS_EXCLUSION_STRATEGY =
new AnonymousAndLocalClassExclusionStrategy();
static final SyntheticFieldExclusionStrategy DEFAULT_SYNTHETIC_FIELD_EXCLUSION_STRATEGY =
new SyntheticFieldExclusionStrategy(true);
static final ModifierBasedExclusionStrategy DEFAULT_MODIFIER_BASED_EXCLUSION_STRATEGY =
new ModifierBasedExclusionStrategy(true, new int[] { Modifier.TRANSIENT, Modifier.STATIC });
new ModifierBasedExclusionStrategy(new int[] { Modifier.TRANSIENT, Modifier.STATIC });
static final JsonFormatter DEFAULT_JSON_FORMATTER = new JsonCompactFormatter();
static final FieldNamingStrategy DEFAULT_NAMING_POLICY =
new SerializedNameAnnotationInterceptingNamingPolicy(new JavaFieldNamingPolicy());
private static final ExclusionStrategy DEFAULT_EXCLUSION_STRATEGY =
createExclusionStrategy(VersionConstants.IGNORE_VERSIONS);
private static final String JSON_NON_EXECUTABLE_PREFIX = ")]}'\n";
private final ExclusionStrategy serializationStrategy;
@ -140,18 +147,10 @@ public final class Gson {
* </ul>
*/
public Gson() {
this(createExclusionStrategy(VersionConstants.IGNORE_VERSIONS), DEFAULT_NAMING_POLICY);
}
/**
* Constructs a Gson object with the specified version and the mode of operation while
* encountering inner class references.
*/
Gson(ExclusionStrategy strategy, FieldNamingStrategy fieldNamingPolicy) {
this(strategy, strategy, fieldNamingPolicy,
new MappedObjectConstructor(DefaultTypeAdapters.getDefaultInstanceCreators()),
DEFAULT_JSON_FORMATTER, false, DefaultTypeAdapters.getDefaultSerializers(),
DefaultTypeAdapters.getDefaultDeserializers(), DEFAULT_JSON_NON_EXECUTABLE);
this(DEFAULT_EXCLUSION_STRATEGY, DEFAULT_EXCLUSION_STRATEGY, DEFAULT_NAMING_POLICY,
new MappedObjectConstructor(DefaultTypeAdapters.getDefaultInstanceCreators()),
DEFAULT_JSON_FORMATTER, false, DefaultTypeAdapters.getDefaultSerializers(),
DefaultTypeAdapters.getDefaultDeserializers(), DEFAULT_JSON_NON_EXECUTABLE);
}
Gson(ExclusionStrategy serializationStrategy, ExclusionStrategy deserializationStrategy,
@ -177,7 +176,8 @@ public final class Gson {
private static ExclusionStrategy createExclusionStrategy(double version) {
List<ExclusionStrategy> strategies = new LinkedList<ExclusionStrategy>();
strategies.add(new AnonymousAndLocalClassExclusionStrategy());
strategies.add(DEFAULT_ANON_LOCAL_CLASS_EXCLUSION_STRATEGY);
strategies.add(DEFAULT_SYNTHETIC_FIELD_EXCLUSION_STRATEGY);
strategies.add(DEFAULT_MODIFIER_BASED_EXCLUSION_STRATEGY);
if (version != VersionConstants.IGNORE_VERSIONS) {
strategies.add(new VersionExclusionStrategy(version));

View File

@ -18,7 +18,9 @@ package com.google.gson;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
@ -50,8 +52,6 @@ import com.google.gson.DefaultTypeAdapters.DefaultDateTypeAdapter;
* @author Joel Leitch
*/
public final class GsonBuilder {
private static final AnonymousAndLocalClassExclusionStrategy anonAndLocalClassExclusionStrategy =
new AnonymousAndLocalClassExclusionStrategy();
private static final InnerClassExclusionStrategy innerClassExclusionStrategy =
new InnerClassExclusionStrategy();
private static final ExposeAnnotationSerializationExclusionStrategy
@ -61,6 +61,9 @@ public final class GsonBuilder {
exposeAnnotationDeserializationExclusionStrategy =
new ExposeAnnotationDeserializationExclusionStrategy();
private final Collection<ExclusionStrategy> exclusionStrategies =
new HashSet<ExclusionStrategy>();
private double ignoreVersionsAfter;
private ModifierBasedExclusionStrategy modifierBasedExclusionStrategy;
private boolean serializeInnerClasses;
@ -86,6 +89,10 @@ public final class GsonBuilder {
* {@link #create()}.
*/
public GsonBuilder() {
// add default exclusion strategies
exclusionStrategies.add(Gson.DEFAULT_ANON_LOCAL_CLASS_EXCLUSION_STRATEGY);
exclusionStrategies.add(Gson.DEFAULT_SYNTHETIC_FIELD_EXCLUSION_STRATEGY);
// setup default values
ignoreVersionsAfter = VersionConstants.IGNORE_VERSIONS;
serializeInnerClasses = true;
@ -129,8 +136,7 @@ public final class GsonBuilder {
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
*/
public GsonBuilder excludeFieldsWithModifiers(int... modifiers) {
boolean skipSynthetics = true;
modifierBasedExclusionStrategy = new ModifierBasedExclusionStrategy(skipSynthetics, modifiers);
modifierBasedExclusionStrategy = new ModifierBasedExclusionStrategy(modifiers);
return this;
}
@ -217,7 +223,24 @@ public final class GsonBuilder {
*/
public GsonBuilder setFieldNamingStrategy(FieldNamingStrategy fieldNamingStrategy) {
this.fieldNamingPolicy =
new SerializedNameAnnotationInterceptingNamingPolicy(fieldNamingStrategy);
new SerializedNameAnnotationInterceptingNamingPolicy(fieldNamingStrategy);
return this;
}
/**
* Configures Gson to apply a set of exclusion strategies during both serialization and
* deserialization. Each of the {@code strategies} will be applied as a disjunctive rule.
* This means that if one of the {@code strategies} suggests that a field (or class) should be
* skipped then that field (or object) is skipped during serializaiton/deserialization.
*
* @param strategies the set of strategy object to apply during object (de)serialization.
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
* @since 1.4
*/
GsonBuilder setExclusionStrategies(ExclusionStrategy... strategies) {
for (ExclusionStrategy strategy : strategies) {
exclusionStrategies.add(strategy);
}
return this;
}
@ -412,12 +435,13 @@ public final class GsonBuilder {
* @return an instance of Gson configured with the options currently set in this builder
*/
public Gson create() {
List<ExclusionStrategy> serializationStrategies = new LinkedList<ExclusionStrategy>();
List<ExclusionStrategy> deserializationStrategies = new LinkedList<ExclusionStrategy>();
List<ExclusionStrategy> serializationStrategies =
new LinkedList<ExclusionStrategy>(exclusionStrategies);
List<ExclusionStrategy> deserializationStrategies =
new LinkedList<ExclusionStrategy>(exclusionStrategies);
serializationStrategies.add(modifierBasedExclusionStrategy);
deserializationStrategies.add(modifierBasedExclusionStrategy);
serializationStrategies.add(anonAndLocalClassExclusionStrategy);
deserializationStrategies.add(anonAndLocalClassExclusionStrategy);
if (!serializeInnerClasses) {
serializationStrategies.add(innerClassExclusionStrategy);

View File

@ -16,7 +16,6 @@
package com.google.gson;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
/**
@ -26,8 +25,8 @@ import java.lang.reflect.Modifier;
*/
class InnerClassExclusionStrategy implements ExclusionStrategy {
public boolean shouldSkipField(Field f) {
return isInnerClass(f.getType());
public boolean shouldSkipField(FieldAttributes f) {
return isInnerClass(f.getDeclaredClass());
}
public boolean shouldSkipClass(Class<?> clazz) {

View File

@ -16,7 +16,6 @@
package com.google.gson;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashSet;
@ -28,11 +27,9 @@ import java.util.HashSet;
* @author Joel Leitch
*/
final class ModifierBasedExclusionStrategy implements ExclusionStrategy {
private final boolean skipSyntheticField;
private final Collection<Integer> modifiers;
public ModifierBasedExclusionStrategy(boolean skipSyntheticFields, int... modifiers) {
this.skipSyntheticField = skipSyntheticFields;
public ModifierBasedExclusionStrategy(int... modifiers) {
this.modifiers = new HashSet<Integer>();
if (modifiers != null) {
for (int modifier : modifiers) {
@ -41,13 +38,9 @@ final class ModifierBasedExclusionStrategy implements ExclusionStrategy {
}
}
public boolean shouldSkipField(Field f) {
if (skipSyntheticField && f.isSynthetic()) {
return true;
}
int objectModifiers = f.getModifiers();
public boolean shouldSkipField(FieldAttributes f) {
for (int modifier : modifiers) {
if ((objectModifiers & modifier) != 0) {
if (f.hasModifier(modifier)) {
return true;
}
}

View File

@ -16,7 +16,6 @@
package com.google.gson;
import java.lang.reflect.Field;
/**
* This acts as a "Null Object" pattern for the {@link ExclusionStrategy}.
@ -28,7 +27,7 @@ import java.lang.reflect.Field;
*/
final class NullExclusionStrategy implements ExclusionStrategy {
public boolean shouldSkipField(Field f) {
public boolean shouldSkipField(FieldAttributes f) {
return false;
}

View File

@ -141,7 +141,7 @@ final class ObjectNavigator {
Field[] fields = clazz.getDeclaredFields();
AccessibleObject.setAccessible(fields, true);
for (Field f : fields) {
if (exclusionStrategy.shouldSkipField(f)) {
if (exclusionStrategy.shouldSkipField(new FieldAttributes(f))) {
continue; // skip
} else {
TypeInfo fieldTypeInfo = TypeInfoFactory.getTypeInfoForField(f, objTypePair.getType());

View File

@ -0,0 +1,44 @@
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson;
/**
* A data object that stores attributes of a field.
*
* <p>This class is immutable; therefore, it can be safely shared across threads.
*
* @author Inderjeet Singh
* @author Joel Leitch
*
* @since 1.4
*/
class SyntheticFieldExclusionStrategy implements ExclusionStrategy {
private final boolean skipSyntheticFields;
SyntheticFieldExclusionStrategy(boolean skipSyntheticFields) {
this.skipSyntheticFields = skipSyntheticFields;
}
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
public boolean shouldSkipField(FieldAttributes f) {
return skipSyntheticFields && f.isSynthetic();
}
}

View File

@ -19,9 +19,6 @@ package com.google.gson;
import com.google.gson.annotations.Since;
import com.google.gson.annotations.Until;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
/**
* This strategy will exclude any files and/or class that are passed the
* {@link #version} value.
@ -36,26 +33,21 @@ final class VersionExclusionStrategy implements ExclusionStrategy {
this.version = version;
}
public boolean shouldSkipField(Field f) {
return !isValidVersion(f.getAnnotations());
public boolean shouldSkipField(FieldAttributes f) {
return !isValidVersion(f.getAnnotation(Since.class), f.getAnnotation(Until.class));
}
public boolean shouldSkipClass(Class<?> clazz) {
return !isValidVersion(clazz.getAnnotations());
return !isValidVersion(clazz.getAnnotation(Since.class), clazz.getAnnotation(Until.class));
}
private boolean isValidVersion(Annotation[] annotations) {
for (Annotation annotation : annotations) {
if (!isValidSince(annotation) || !isValidUntil(annotation)) {
return false;
}
}
return true;
private boolean isValidVersion(Since since, Until until) {
return (isValidSince(since) && isValidUntil(until));
}
private boolean isValidSince(Annotation annotation) {
if (annotation instanceof Since) {
double annotationVersion = ((Since) annotation).value();
private boolean isValidSince(Since annotation) {
if (annotation != null) {
double annotationVersion = annotation.value();
if (annotationVersion > version) {
return false;
}
@ -63,9 +55,9 @@ final class VersionExclusionStrategy implements ExclusionStrategy {
return true;
}
private boolean isValidUntil(Annotation annotation) {
if (annotation instanceof Until) {
double annotationVersion = ((Until) annotation).value();
private boolean isValidUntil(Until annotation) {
if (annotation != null) {
double annotationVersion = annotation.value();
if (annotationVersion <= version) {
return false;
}

View File

@ -16,15 +16,11 @@
package com.google.gson;
import com.google.gson.DisjunctionExclusionStrategy;
import com.google.gson.ExclusionStrategy;
import junit.framework.TestCase;
import java.lang.reflect.Field;
import java.util.LinkedList;
import java.util.List;
import junit.framework.TestCase;
/**
* Unit tests for the {@link DisjunctionExclusionStrategy} class.
*
@ -35,12 +31,13 @@ public class DisjunctionExclusionStrategyTest extends TestCase {
private static final ExclusionStrategy FALSE_STRATEGY = new MockExclusionStrategy(false, false);
private static final ExclusionStrategy TRUE_STRATEGY = new MockExclusionStrategy(true, true);
private static final Class<?> CLAZZ = String.class;
private static final Field FIELD = CLAZZ.getFields()[0];
private static final FieldAttributes FIELD = new FieldAttributes(CLAZZ.getFields()[0]);
public void testBadInstantiation() throws Exception {
try {
List<ExclusionStrategy> constructorParam = null;
new DisjunctionExclusionStrategy(constructorParam);
fail("Should throw an exception");
} catch (IllegalArgumentException expected) { }
}

View File

@ -42,22 +42,22 @@ public class ExposeAnnotationDeserializationExclusionStrategyTest extends TestCa
public void testSkipNonAnnotatedFields() throws Exception {
Field f = MockObject.class.getField("hiddenField");
assertTrue(strategy.shouldSkipField(f));
assertTrue(strategy.shouldSkipField(new FieldAttributes(f)));
}
public void testSkipExplicitlySkippedFields() throws Exception {
Field f = MockObject.class.getField("explicitlyHiddenField");
assertTrue(strategy.shouldSkipField(f));
assertTrue(strategy.shouldSkipField(new FieldAttributes(f)));
}
public void testNeverSkipExposedAnnotatedFields() throws Exception {
Field f = MockObject.class.getField("exposedField");
assertFalse(strategy.shouldSkipField(f));
assertFalse(strategy.shouldSkipField(new FieldAttributes(f)));
}
public void testNeverSkipExplicitlyExposedAnnotatedFields() throws Exception {
Field f = MockObject.class.getField("explicitlyExposedField");
assertFalse(strategy.shouldSkipField(f));
assertFalse(strategy.shouldSkipField(new FieldAttributes(f)));
}
@SuppressWarnings("unused")

View File

@ -42,22 +42,22 @@ public class ExposeAnnotationSerializationExclusionStrategyTest extends TestCase
public void testSkipNonAnnotatedFields() throws Exception {
Field f = MockObject.class.getField("hiddenField");
assertTrue(strategy.shouldSkipField(f));
assertTrue(strategy.shouldSkipField(new FieldAttributes(f)));
}
public void testSkipExplicitlySkippedFields() throws Exception {
Field f = MockObject.class.getField("explicitlyHiddenField");
assertTrue(strategy.shouldSkipField(f));
assertTrue(strategy.shouldSkipField(new FieldAttributes(f)));
}
public void testNeverSkipExposedAnnotatedFields() throws Exception {
Field f = MockObject.class.getField("exposedField");
assertFalse(strategy.shouldSkipField(f));
assertFalse(strategy.shouldSkipField(new FieldAttributes(f)));
}
public void testNeverSkipExplicitlyExposedAnnotatedFields() throws Exception {
Field f = MockObject.class.getField("explicitlyExposedField");
assertFalse(strategy.shouldSkipField(f));
assertFalse(strategy.shouldSkipField(new FieldAttributes(f)));
}
@SuppressWarnings("unused")

View File

@ -0,0 +1,77 @@
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.List;
import junit.framework.TestCase;
import com.google.gson.reflect.TypeToken;
/**
* Unit tests for the {@link FieldAttributes} class.
*
* @author Inderjeet Singh
* @author Joel Leitch
*/
public class FieldAttributesTest extends TestCase {
private FieldAttributes fieldAttributes;
@Override
protected void setUp() throws Exception {
super.setUp();
fieldAttributes = new FieldAttributes(Foo.class.getField("bar"));
}
public void testNullField() throws Exception {
try {
new FieldAttributes(null);
fail("Field parameter can not be null");
} catch (IllegalArgumentException expected) { }
}
public void testModifiers() throws Exception {
assertFalse(fieldAttributes.hasModifier(Modifier.STATIC));
assertFalse(fieldAttributes.hasModifier(Modifier.FINAL));
assertFalse(fieldAttributes.hasModifier(Modifier.ABSTRACT));
assertFalse(fieldAttributes.hasModifier(Modifier.VOLATILE));
assertFalse(fieldAttributes.hasModifier(Modifier.PROTECTED));
assertTrue(fieldAttributes.hasModifier(Modifier.PUBLIC));
assertTrue(fieldAttributes.hasModifier(Modifier.TRANSIENT));
}
public void testIsSynthetic() throws Exception {
assertFalse(fieldAttributes.isSynthetic());
}
public void testName() throws Exception {
assertEquals("bar", fieldAttributes.getName());
}
public void testDeclaredTypeAndClass() throws Exception {
Type expectedType = new TypeToken<List<String>>() {}.getType();
assertEquals(expectedType, fieldAttributes.getDeclaredType());
assertEquals(List.class, fieldAttributes.getDeclaredClass());
}
private static class Foo {
public transient List<String> bar;
}
}

View File

@ -16,11 +16,13 @@
package com.google.gson;
import com.google.gson.common.TestTypes.ClassWithNoFields;
import java.lang.reflect.Modifier;
import java.util.LinkedList;
import junit.framework.TestCase;
import java.lang.reflect.Modifier;
import com.google.gson.common.TestTypes;
import com.google.gson.common.TestTypes.ClassWithNoFields;
/**
* Functional tests for Gson that depend on some internal package-protected elements of
@ -32,11 +34,45 @@ import java.lang.reflect.Modifier;
*/
public class FunctionWithInternalDependenciesTest extends TestCase {
public void testAnonymousLocalClassesSerialization() {
Gson gson = new Gson(new ModifierBasedExclusionStrategy(
true, Modifier.TRANSIENT, Modifier.STATIC), Gson.DEFAULT_NAMING_POLICY);
public void testAnonymousLocalClassesSerialization() throws Exception {
LinkedList<ExclusionStrategy> strategies = new LinkedList<ExclusionStrategy>();
strategies.add(new SyntheticFieldExclusionStrategy(true));
strategies.add(new ModifierBasedExclusionStrategy(Modifier.TRANSIENT, Modifier.STATIC));
ExclusionStrategy exclusionStrategy = new DisjunctionExclusionStrategy(strategies);
Gson gson = new Gson(exclusionStrategy, exclusionStrategy, Gson.DEFAULT_NAMING_POLICY,
new MappedObjectConstructor(DefaultTypeAdapters.getDefaultInstanceCreators()),
Gson.DEFAULT_JSON_FORMATTER, false, DefaultTypeAdapters.getDefaultSerializers(),
DefaultTypeAdapters.getDefaultDeserializers(), Gson.DEFAULT_JSON_NON_EXECUTABLE);
assertEquals("{}", gson.toJson(new ClassWithNoFields() {
// empty anonymous class
}));
}
// TODO(Joel): Move this to some other functional test once exclusion policies are
// available to the public
public void testUserDefinedExclusionPolicies() throws Exception {
Gson gson = new GsonBuilder()
.setExclusionStrategies(new UserDefinedExclusionStrategy(String.class))
.create();
String json = gson.toJson(new TestTypes.StringWrapper("someValue"));
assertEquals("{}", json);
}
private static class UserDefinedExclusionStrategy implements ExclusionStrategy {
private final Class<?> excludedThisClass;
UserDefinedExclusionStrategy(Class<?> excludedThisClass) {
this.excludedThisClass = excludedThisClass;
}
public boolean shouldSkipClass(Class<?> clazz) {
return excludedThisClass.equals(clazz);
}
public boolean shouldSkipField(FieldAttributes f) {
return excludedThisClass.equals(f.getDeclaredClass());
}
}
}

View File

@ -46,7 +46,7 @@ public class InnerClassExclusionStrategyTest extends TestCase {
public void testExcludeInnerClassField() throws Exception {
Field f = getClass().getField("innerClass");
assertTrue(strategy.shouldSkipField(f));
assertTrue(strategy.shouldSkipField(new FieldAttributes(f)));
}
public void testIncludeStaticNestedClassObject() throws Exception {
@ -56,7 +56,7 @@ public class InnerClassExclusionStrategyTest extends TestCase {
public void testIncludeStaticNestedClassField() throws Exception {
Field f = getClass().getField("staticNestedClass");
assertFalse(strategy.shouldSkipField(f));
assertFalse(strategy.shouldSkipField(new FieldAttributes(f)));
}
class InnerClass {

View File

@ -16,9 +16,6 @@
package com.google.gson;
import com.google.gson.ExclusionStrategy;
import java.lang.reflect.Field;
/**
* This is a configurable {@link ExclusionStrategy} that can be used for
@ -35,7 +32,7 @@ public class MockExclusionStrategy implements ExclusionStrategy {
this.skipField = skipField;
}
public boolean shouldSkipField(Field f) {
public boolean shouldSkipField(FieldAttributes f) {
return skipField;
}

View File

@ -16,8 +16,6 @@
package com.google.gson;
import com.google.gson.NullExclusionStrategy;
import junit.framework.TestCase;
/**
@ -39,6 +37,7 @@ public class NullExclusionStrategyTest extends TestCase {
}
public void testNeverSkipsField() throws Exception {
assertFalse(strategy.shouldSkipField("".getClass().getFields()[0]));
assertFalse(strategy.shouldSkipField(
new FieldAttributes("".getClass().getFields()[0])));
}
}

View File

@ -16,11 +16,11 @@
package com.google.gson;
import com.google.gson.annotations.Since;
import java.lang.reflect.Field;
import junit.framework.TestCase;
import java.lang.reflect.Field;
import com.google.gson.annotations.Since;
/**
* Unit tests for the {@link VersionExclusionStrategy} class.
@ -43,7 +43,7 @@ public class VersionExclusionStrategyTest extends TestCase {
VersionExclusionStrategy strategy = new VersionExclusionStrategy(VERSION);
assertFalse(strategy.shouldSkipClass(clazz));
assertFalse(strategy.shouldSkipField(f));
assertFalse(strategy.shouldSkipField(new FieldAttributes(f)));
}
public void testClassAndFieldAreBehindInVersion() throws Exception {
@ -52,7 +52,7 @@ public class VersionExclusionStrategyTest extends TestCase {
VersionExclusionStrategy strategy = new VersionExclusionStrategy(VERSION + 1);
assertFalse(strategy.shouldSkipClass(clazz));
assertFalse(strategy.shouldSkipField(f));
assertFalse(strategy.shouldSkipField(new FieldAttributes(f)));
}
public void testClassAndFieldAreAheadInVersion() throws Exception {
@ -61,7 +61,7 @@ public class VersionExclusionStrategyTest extends TestCase {
VersionExclusionStrategy strategy = new VersionExclusionStrategy(VERSION - 1);
assertTrue(strategy.shouldSkipClass(clazz));
assertTrue(strategy.shouldSkipField(f));
assertTrue(strategy.shouldSkipField(new FieldAttributes(f)));
}
@Since(VERSION)