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

View File

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

View File

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

View File

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

View File

@ -18,8 +18,6 @@ package com.google.gson;
import com.google.gson.annotations.Expose; import com.google.gson.annotations.Expose;
import java.lang.reflect.Field;
/** /**
* Excludes fields that do not have the {@link Expose} annotation * Excludes fields that do not have the {@link Expose} annotation
* *
@ -32,7 +30,7 @@ final class ExposeAnnotationSerializationExclusionStrategy implements ExclusionS
return false; return false;
} }
public boolean shouldSkipField(Field f) { public boolean shouldSkipField(FieldAttributes f) {
Expose annotation = f.getAnnotation(Expose.class); Expose annotation = f.getAnnotation(Expose.class);
if (annotation == null) { if (annotation == null) {
return true; 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; static final boolean DEFAULT_JSON_NON_EXECUTABLE = false;
// Default instances of plug-ins // 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 = 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 JsonFormatter DEFAULT_JSON_FORMATTER = new JsonCompactFormatter();
static final FieldNamingStrategy DEFAULT_NAMING_POLICY = static final FieldNamingStrategy DEFAULT_NAMING_POLICY =
new SerializedNameAnnotationInterceptingNamingPolicy(new JavaFieldNamingPolicy()); 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 static final String JSON_NON_EXECUTABLE_PREFIX = ")]}'\n";
private final ExclusionStrategy serializationStrategy; private final ExclusionStrategy serializationStrategy;
@ -140,15 +147,7 @@ public final class Gson {
* </ul> * </ul>
*/ */
public Gson() { public Gson() {
this(createExclusionStrategy(VersionConstants.IGNORE_VERSIONS), DEFAULT_NAMING_POLICY); this(DEFAULT_EXCLUSION_STRATEGY, DEFAULT_EXCLUSION_STRATEGY, 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()), new MappedObjectConstructor(DefaultTypeAdapters.getDefaultInstanceCreators()),
DEFAULT_JSON_FORMATTER, false, DefaultTypeAdapters.getDefaultSerializers(), DEFAULT_JSON_FORMATTER, false, DefaultTypeAdapters.getDefaultSerializers(),
DefaultTypeAdapters.getDefaultDeserializers(), DEFAULT_JSON_NON_EXECUTABLE); DefaultTypeAdapters.getDefaultDeserializers(), DEFAULT_JSON_NON_EXECUTABLE);
@ -177,7 +176,8 @@ public final class Gson {
private static ExclusionStrategy createExclusionStrategy(double version) { private static ExclusionStrategy createExclusionStrategy(double version) {
List<ExclusionStrategy> strategies = new LinkedList<ExclusionStrategy>(); 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); strategies.add(DEFAULT_MODIFIER_BASED_EXCLUSION_STRATEGY);
if (version != VersionConstants.IGNORE_VERSIONS) { if (version != VersionConstants.IGNORE_VERSIONS) {
strategies.add(new VersionExclusionStrategy(version)); strategies.add(new VersionExclusionStrategy(version));

View File

@ -18,7 +18,9 @@ package com.google.gson;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.text.DateFormat; import java.text.DateFormat;
import java.util.Collection;
import java.util.Date; import java.util.Date;
import java.util.HashSet;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
@ -50,8 +52,6 @@ import com.google.gson.DefaultTypeAdapters.DefaultDateTypeAdapter;
* @author Joel Leitch * @author Joel Leitch
*/ */
public final class GsonBuilder { public final class GsonBuilder {
private static final AnonymousAndLocalClassExclusionStrategy anonAndLocalClassExclusionStrategy =
new AnonymousAndLocalClassExclusionStrategy();
private static final InnerClassExclusionStrategy innerClassExclusionStrategy = private static final InnerClassExclusionStrategy innerClassExclusionStrategy =
new InnerClassExclusionStrategy(); new InnerClassExclusionStrategy();
private static final ExposeAnnotationSerializationExclusionStrategy private static final ExposeAnnotationSerializationExclusionStrategy
@ -61,6 +61,9 @@ public final class GsonBuilder {
exposeAnnotationDeserializationExclusionStrategy = exposeAnnotationDeserializationExclusionStrategy =
new ExposeAnnotationDeserializationExclusionStrategy(); new ExposeAnnotationDeserializationExclusionStrategy();
private final Collection<ExclusionStrategy> exclusionStrategies =
new HashSet<ExclusionStrategy>();
private double ignoreVersionsAfter; private double ignoreVersionsAfter;
private ModifierBasedExclusionStrategy modifierBasedExclusionStrategy; private ModifierBasedExclusionStrategy modifierBasedExclusionStrategy;
private boolean serializeInnerClasses; private boolean serializeInnerClasses;
@ -86,6 +89,10 @@ public final class GsonBuilder {
* {@link #create()}. * {@link #create()}.
*/ */
public GsonBuilder() { 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 // setup default values
ignoreVersionsAfter = VersionConstants.IGNORE_VERSIONS; ignoreVersionsAfter = VersionConstants.IGNORE_VERSIONS;
serializeInnerClasses = true; serializeInnerClasses = true;
@ -129,8 +136,7 @@ public final class GsonBuilder {
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
*/ */
public GsonBuilder excludeFieldsWithModifiers(int... modifiers) { public GsonBuilder excludeFieldsWithModifiers(int... modifiers) {
boolean skipSynthetics = true; modifierBasedExclusionStrategy = new ModifierBasedExclusionStrategy(modifiers);
modifierBasedExclusionStrategy = new ModifierBasedExclusionStrategy(skipSynthetics, modifiers);
return this; return this;
} }
@ -221,6 +227,23 @@ public final class GsonBuilder {
return this; 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;
}
/** /**
* Configures Gson to output Json that fits in a page for pretty printing. This option only * Configures Gson to output Json that fits in a page for pretty printing. This option only
* affects Json serialization. * affects Json serialization.
@ -412,12 +435,13 @@ public final class GsonBuilder {
* @return an instance of Gson configured with the options currently set in this builder * @return an instance of Gson configured with the options currently set in this builder
*/ */
public Gson create() { public Gson create() {
List<ExclusionStrategy> serializationStrategies = new LinkedList<ExclusionStrategy>(); List<ExclusionStrategy> serializationStrategies =
List<ExclusionStrategy> deserializationStrategies = new LinkedList<ExclusionStrategy>(); new LinkedList<ExclusionStrategy>(exclusionStrategies);
List<ExclusionStrategy> deserializationStrategies =
new LinkedList<ExclusionStrategy>(exclusionStrategies);
serializationStrategies.add(modifierBasedExclusionStrategy); serializationStrategies.add(modifierBasedExclusionStrategy);
deserializationStrategies.add(modifierBasedExclusionStrategy); deserializationStrategies.add(modifierBasedExclusionStrategy);
serializationStrategies.add(anonAndLocalClassExclusionStrategy);
deserializationStrategies.add(anonAndLocalClassExclusionStrategy);
if (!serializeInnerClasses) { if (!serializeInnerClasses) {
serializationStrategies.add(innerClassExclusionStrategy); serializationStrategies.add(innerClassExclusionStrategy);

View File

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

View File

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

View File

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

View File

@ -141,7 +141,7 @@ final class ObjectNavigator {
Field[] fields = clazz.getDeclaredFields(); Field[] fields = clazz.getDeclaredFields();
AccessibleObject.setAccessible(fields, true); AccessibleObject.setAccessible(fields, true);
for (Field f : fields) { for (Field f : fields) {
if (exclusionStrategy.shouldSkipField(f)) { if (exclusionStrategy.shouldSkipField(new FieldAttributes(f))) {
continue; // skip continue; // skip
} else { } else {
TypeInfo fieldTypeInfo = TypeInfoFactory.getTypeInfoForField(f, objTypePair.getType()); 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.Since;
import com.google.gson.annotations.Until; 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 * This strategy will exclude any files and/or class that are passed the
* {@link #version} value. * {@link #version} value.
@ -36,26 +33,21 @@ final class VersionExclusionStrategy implements ExclusionStrategy {
this.version = version; this.version = version;
} }
public boolean shouldSkipField(Field f) { public boolean shouldSkipField(FieldAttributes f) {
return !isValidVersion(f.getAnnotations()); return !isValidVersion(f.getAnnotation(Since.class), f.getAnnotation(Until.class));
} }
public boolean shouldSkipClass(Class<?> clazz) { public boolean shouldSkipClass(Class<?> clazz) {
return !isValidVersion(clazz.getAnnotations()); return !isValidVersion(clazz.getAnnotation(Since.class), clazz.getAnnotation(Until.class));
} }
private boolean isValidVersion(Annotation[] annotations) { private boolean isValidVersion(Since since, Until until) {
for (Annotation annotation : annotations) { return (isValidSince(since) && isValidUntil(until));
if (!isValidSince(annotation) || !isValidUntil(annotation)) {
return false;
}
}
return true;
} }
private boolean isValidSince(Annotation annotation) { private boolean isValidSince(Since annotation) {
if (annotation instanceof Since) { if (annotation != null) {
double annotationVersion = ((Since) annotation).value(); double annotationVersion = annotation.value();
if (annotationVersion > version) { if (annotationVersion > version) {
return false; return false;
} }
@ -63,9 +55,9 @@ final class VersionExclusionStrategy implements ExclusionStrategy {
return true; return true;
} }
private boolean isValidUntil(Annotation annotation) { private boolean isValidUntil(Until annotation) {
if (annotation instanceof Until) { if (annotation != null) {
double annotationVersion = ((Until) annotation).value(); double annotationVersion = annotation.value();
if (annotationVersion <= version) { if (annotationVersion <= version) {
return false; return false;
} }

View File

@ -16,15 +16,11 @@
package com.google.gson; 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.LinkedList;
import java.util.List; import java.util.List;
import junit.framework.TestCase;
/** /**
* Unit tests for the {@link DisjunctionExclusionStrategy} class. * 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 FALSE_STRATEGY = new MockExclusionStrategy(false, false);
private static final ExclusionStrategy TRUE_STRATEGY = new MockExclusionStrategy(true, true); private static final ExclusionStrategy TRUE_STRATEGY = new MockExclusionStrategy(true, true);
private static final Class<?> CLAZZ = String.class; 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 { public void testBadInstantiation() throws Exception {
try { try {
List<ExclusionStrategy> constructorParam = null; List<ExclusionStrategy> constructorParam = null;
new DisjunctionExclusionStrategy(constructorParam); new DisjunctionExclusionStrategy(constructorParam);
fail("Should throw an exception");
} catch (IllegalArgumentException expected) { } } catch (IllegalArgumentException expected) { }
} }

View File

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

View File

@ -42,22 +42,22 @@ public class ExposeAnnotationSerializationExclusionStrategyTest extends TestCase
public void testSkipNonAnnotatedFields() throws Exception { public void testSkipNonAnnotatedFields() throws Exception {
Field f = MockObject.class.getField("hiddenField"); Field f = MockObject.class.getField("hiddenField");
assertTrue(strategy.shouldSkipField(f)); assertTrue(strategy.shouldSkipField(new FieldAttributes(f)));
} }
public void testSkipExplicitlySkippedFields() throws Exception { public void testSkipExplicitlySkippedFields() throws Exception {
Field f = MockObject.class.getField("explicitlyHiddenField"); Field f = MockObject.class.getField("explicitlyHiddenField");
assertTrue(strategy.shouldSkipField(f)); assertTrue(strategy.shouldSkipField(new FieldAttributes(f)));
} }
public void testNeverSkipExposedAnnotatedFields() throws Exception { public void testNeverSkipExposedAnnotatedFields() throws Exception {
Field f = MockObject.class.getField("exposedField"); Field f = MockObject.class.getField("exposedField");
assertFalse(strategy.shouldSkipField(f)); assertFalse(strategy.shouldSkipField(new FieldAttributes(f)));
} }
public void testNeverSkipExplicitlyExposedAnnotatedFields() throws Exception { public void testNeverSkipExplicitlyExposedAnnotatedFields() throws Exception {
Field f = MockObject.class.getField("explicitlyExposedField"); Field f = MockObject.class.getField("explicitlyExposedField");
assertFalse(strategy.shouldSkipField(f)); assertFalse(strategy.shouldSkipField(new FieldAttributes(f)));
} }
@SuppressWarnings("unused") @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; 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 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 * 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 class FunctionWithInternalDependenciesTest extends TestCase {
public void testAnonymousLocalClassesSerialization() { public void testAnonymousLocalClassesSerialization() throws Exception {
Gson gson = new Gson(new ModifierBasedExclusionStrategy( LinkedList<ExclusionStrategy> strategies = new LinkedList<ExclusionStrategy>();
true, Modifier.TRANSIENT, Modifier.STATIC), Gson.DEFAULT_NAMING_POLICY); 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() { assertEquals("{}", gson.toJson(new ClassWithNoFields() {
// empty anonymous class // 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 { public void testExcludeInnerClassField() throws Exception {
Field f = getClass().getField("innerClass"); Field f = getClass().getField("innerClass");
assertTrue(strategy.shouldSkipField(f)); assertTrue(strategy.shouldSkipField(new FieldAttributes(f)));
} }
public void testIncludeStaticNestedClassObject() throws Exception { public void testIncludeStaticNestedClassObject() throws Exception {
@ -56,7 +56,7 @@ public class InnerClassExclusionStrategyTest extends TestCase {
public void testIncludeStaticNestedClassField() throws Exception { public void testIncludeStaticNestedClassField() throws Exception {
Field f = getClass().getField("staticNestedClass"); Field f = getClass().getField("staticNestedClass");
assertFalse(strategy.shouldSkipField(f)); assertFalse(strategy.shouldSkipField(new FieldAttributes(f)));
} }
class InnerClass { class InnerClass {

View File

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

View File

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