io.honeybadger.com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector Maven / Gradle / Ivy
package com.fasterxml.jackson.databind.introspect;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.*;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.*;
import com.fasterxml.jackson.databind.cfg.HandlerInstantiator;
import com.fasterxml.jackson.databind.cfg.MapperConfig;
import com.fasterxml.jackson.databind.ext.Java7Support;
import com.fasterxml.jackson.databind.jsontype.NamedType;
import com.fasterxml.jackson.databind.jsontype.TypeIdResolver;
import com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder;
import com.fasterxml.jackson.databind.jsontype.impl.StdTypeResolverBuilder;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.VirtualBeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.impl.AttributePropertyWriter;
import com.fasterxml.jackson.databind.ser.std.RawSerializer;
import com.fasterxml.jackson.databind.util.*;
/**
* {@link AnnotationIntrospector} implementation that handles standard
* Jackson annotations.
*/
public class JacksonAnnotationIntrospector
extends AnnotationIntrospector
implements java.io.Serializable
{
private static final long serialVersionUID = 1L;
@SuppressWarnings("unchecked")
private final static Class extends Annotation>[] ANNOTATIONS_TO_INFER_SER = (Class extends Annotation>[])
new Class>[] {
JsonSerialize.class,
JsonView.class,
JsonFormat.class,
JsonTypeInfo.class,
JsonRawValue.class,
JsonUnwrapped.class,
JsonBackReference.class,
JsonManagedReference.class
};
@SuppressWarnings("unchecked")
private final static Class extends Annotation>[] ANNOTATIONS_TO_INFER_DESER = (Class extends Annotation>[])
new Class>[] {
JsonDeserialize.class,
JsonView.class,
JsonFormat.class,
JsonTypeInfo.class,
JsonUnwrapped.class,
JsonBackReference.class,
JsonManagedReference.class
};
// NOTE: loading of Java7 dependencies is encapsulated by handlers in Java7Support,
// here we do not really need any handling; but for extra-safety use try-catch
private static final Java7Support _java7Helper;
static {
Java7Support x = null;
try {
x = Java7Support.instance();
} catch (Throwable t) { }
_java7Helper = x;
}
/**
* Since introspection of annotation types is a performance issue in some
* use cases (rare, but do exist), let's try a simple cache to reduce
* need for actual meta-annotation introspection.
*
* Non-final only because it needs to be re-created after deserialization.
*
* @since 2.7
*/
protected transient LRUMap,Boolean> _annotationsInside = new LRUMap,Boolean>(48, 48);
/*
/**********************************************************
/* Local configuration settings
/**********************************************************
*/
/**
* See {@link #setConstructorPropertiesImpliesCreator(boolean)} for
* explanation.
*
* Defaults to true.
*
* @since 2.7.4
*/
protected boolean _cfgConstructorPropertiesImpliesCreator = true;
/*
/**********************************************************
/* Life-cycle
/**********************************************************
*/
public JacksonAnnotationIntrospector() { }
@Override
public Version version() {
return com.fasterxml.jackson.databind.cfg.PackageVersion.VERSION;
}
protected Object readResolve() {
if (_annotationsInside == null) {
_annotationsInside = new LRUMap,Boolean>(48, 48);
}
return this;
}
/*
/**********************************************************
/* Configuration
/**********************************************************
*/
/**
* Method for changing behavior of {@link java.beans.ConstructorProperties}:
* if set to `true`, existence DOES indicate that the given constructor should
* be considered a creator; `false` that it should NOT be considered a creator
* without explicit use of JsonCreator
annotation.
*
* Default setting is `true`
*
* @since 2.7.4
*/
public JacksonAnnotationIntrospector setConstructorPropertiesImpliesCreator(boolean b)
{
_cfgConstructorPropertiesImpliesCreator = b;
return this;
}
/*
/**********************************************************
/* General annotation properties
/**********************************************************
*/
/**
* Annotations with meta-annotation {@link JacksonAnnotationsInside}
* are considered bundles.
*/
@Override
public boolean isAnnotationBundle(Annotation ann) {
// 22-Sep-2015, tatu: Caching here has modest effect on JavaSE, and only
// mostly in degenerate cases where introspection used more often than
// it should (like recreating ObjectMapper once per read/write).
// But it may be more beneficial on platforms like Android (should verify)
Class> type = ann.annotationType();
Boolean b = _annotationsInside.get(type);
if (b == null) {
b = type.getAnnotation(JacksonAnnotationsInside.class) != null;
_annotationsInside.putIfAbsent(type, b);
}
return b.booleanValue();
}
/*
/**********************************************************
/* General annotations
/**********************************************************
*/
/**
* Since 2.6, we have supported use of {@link JsonProperty} for specifying
* explicit serialized name
*/
@Override
@Deprecated
public String findEnumValue(Enum> value)
{
// 11-Jun-2015, tatu: As per [databind#677], need to allow explicit naming.
// Unfortunately can not quite use standard AnnotatedClass here (due to various
// reasons, including odd representation JVM uses); has to do for now
try {
// We know that values are actually static fields with matching name so:
Field f = value.getClass().getField(value.name());
if (f != null) {
JsonProperty prop = f.getAnnotation(JsonProperty.class);
if (prop != null) {
String n = prop.value();
if (n != null && !n.isEmpty()) {
return n;
}
}
}
} catch (SecurityException e) {
// 17-Sep-2015, tatu: Anything we could/should do here?
} catch (NoSuchFieldException e) {
// 17-Sep-2015, tatu: should not really happen. But... can we do anything?
}
return value.name();
}
@Override // since 2.7
public String[] findEnumValues(Class> enumType, Enum>[] enumValues, String[] names) {
HashMap expl = null;
for (Field f : ClassUtil.getDeclaredFields(enumType)) {
if (!f.isEnumConstant()) {
continue;
}
JsonProperty prop = f.getAnnotation(JsonProperty.class);
if (prop == null) {
continue;
}
String n = prop.value();
if (n.isEmpty()) {
continue;
}
if (expl == null) {
expl = new HashMap();
}
expl.put(f.getName(), n);
}
// and then stitch them together if and as necessary
if (expl != null) {
for (int i = 0, end = enumValues.length; i < end; ++i) {
String defName = enumValues[i].name();
String explValue = expl.get(defName);
if (explValue != null) {
names[i] = explValue;
}
}
}
return names;
}
/**
* Finds the Enum value that should be considered the default value, if possible.
*
* This implementation relies on {@link JsonEnumDefaultValue} annotation to determine the default value if present.
*
* @param enumCls The Enum class to scan for the default value.
* @return null if none found or it's not possible to determine one.
* @since 2.8
*/
@Override
public Enum> findDefaultEnumValue(Class> enumCls) {
return ClassUtil.findFirstAnnotatedEnumValue(enumCls, JsonEnumDefaultValue.class);
}
/*
/**********************************************************
/* General class annotations
/**********************************************************
*/
@Override
public PropertyName findRootName(AnnotatedClass ac)
{
JsonRootName ann = _findAnnotation(ac, JsonRootName.class);
if (ann == null) {
return null;
}
String ns = ann.namespace();
if (ns != null && ns.length() == 0) {
ns = null;
}
return PropertyName.construct(ann.value(), ns);
}
@Override // since 2.8
public JsonIgnoreProperties.Value findPropertyIgnorals(Annotated a)
{
JsonIgnoreProperties v = _findAnnotation(a, JsonIgnoreProperties.class);
if (v == null) {
// could alternatively return `Value.empty()`?
return null;
}
return JsonIgnoreProperties.Value.from(v);
}
@Override // since 2.6
@Deprecated // since 2.8
public String[] findPropertiesToIgnore(Annotated a, boolean forSerialization) {
JsonIgnoreProperties.Value v = findPropertyIgnorals(a);
if (v == null) {
return null;
}
// 13-May-2015, tatu: As per [databind#95], allow read-only/write-only props
if (forSerialization) {
if (v.getAllowGetters()) {
return null;
}
} else {
if (v.getAllowSetters()) {
return null;
}
}
Set ignored = v.getIgnored();
return ignored.toArray(new String[ignored.size()]);
}
@Override
@Deprecated // since 2.8
public Boolean findIgnoreUnknownProperties(AnnotatedClass a) {
JsonIgnoreProperties.Value v = findPropertyIgnorals(a);
return (v == null) ? null : v.getIgnoreUnknown();
}
@Override
public Boolean isIgnorableType(AnnotatedClass ac) {
JsonIgnoreType ignore = _findAnnotation(ac, JsonIgnoreType.class);
return (ignore == null) ? null : ignore.value();
}
@Override
public Object findFilterId(Annotated a) {
JsonFilter ann = _findAnnotation(a, JsonFilter.class);
if (ann != null) {
String id = ann.value();
// Empty String is same as not having annotation, to allow overrides
if (id.length() > 0) {
return id;
}
}
return null;
}
@Override
public Object findNamingStrategy(AnnotatedClass ac)
{
JsonNaming ann = _findAnnotation(ac, JsonNaming.class);
return (ann == null) ? null : ann.value();
}
@Override
public String findClassDescription(AnnotatedClass ac) {
JsonClassDescription ann = _findAnnotation(ac, JsonClassDescription.class);
return (ann == null) ? null : ann.value();
}
/*
/**********************************************************
/* Property auto-detection
/**********************************************************
*/
@Override
public VisibilityChecker> findAutoDetectVisibility(AnnotatedClass ac,
VisibilityChecker> checker)
{
JsonAutoDetect ann = _findAnnotation(ac, JsonAutoDetect.class);
return (ann == null) ? checker : checker.with(ann);
}
/*
/**********************************************************
/* General member (field, method/constructor) annotations
/**********************************************************
*/
@Override
public String findImplicitPropertyName(AnnotatedMember m) {
PropertyName n = _findConstructorName(m);
return (n == null) ? null : n.getSimpleName();
}
@Override
public boolean hasIgnoreMarker(AnnotatedMember m) {
return _isIgnorable(m);
}
@Override
public Boolean hasRequiredMarker(AnnotatedMember m)
{
JsonProperty ann = _findAnnotation(m, JsonProperty.class);
if (ann != null) {
return ann.required();
}
return null;
}
@Override
public JsonProperty.Access findPropertyAccess(Annotated m) {
JsonProperty ann = _findAnnotation(m, JsonProperty.class);
if (ann != null) {
return ann.access();
}
return null;
}
@Override
public String findPropertyDescription(Annotated ann) {
JsonPropertyDescription desc = _findAnnotation(ann, JsonPropertyDescription.class);
return (desc == null) ? null : desc.value();
}
@Override
public Integer findPropertyIndex(Annotated ann) {
JsonProperty prop = _findAnnotation(ann, JsonProperty.class);
if (prop != null) {
int ix = prop.index();
if (ix != JsonProperty.INDEX_UNKNOWN) {
return Integer.valueOf(ix);
}
}
return null;
}
@Override
public String findPropertyDefaultValue(Annotated ann) {
JsonProperty prop = _findAnnotation(ann, JsonProperty.class);
if (prop == null) {
return null;
}
String str = prop.defaultValue();
// Since annotations do not allow nulls, need to assume empty means "none"
return str.isEmpty() ? null : str;
}
@Override
public JsonFormat.Value findFormat(Annotated ann) {
JsonFormat f = _findAnnotation(ann, JsonFormat.class);
return (f == null) ? null : new JsonFormat.Value(f);
}
@Override
public ReferenceProperty findReferenceType(AnnotatedMember member)
{
JsonManagedReference ref1 = _findAnnotation(member, JsonManagedReference.class);
if (ref1 != null) {
return AnnotationIntrospector.ReferenceProperty.managed(ref1.value());
}
JsonBackReference ref2 = _findAnnotation(member, JsonBackReference.class);
if (ref2 != null) {
return AnnotationIntrospector.ReferenceProperty.back(ref2.value());
}
return null;
}
@Override
public NameTransformer findUnwrappingNameTransformer(AnnotatedMember member)
{
JsonUnwrapped ann = _findAnnotation(member, JsonUnwrapped.class);
// if not enabled, just means annotation is not enabled; not necessarily
// that unwrapping should not be done (relevant when using chained introspectors)
if (ann == null || !ann.enabled()) {
return null;
}
String prefix = ann.prefix();
String suffix = ann.suffix();
return NameTransformer.simpleTransformer(prefix, suffix);
}
@Override
public Object findInjectableValueId(AnnotatedMember m)
{
JacksonInject ann = _findAnnotation(m, JacksonInject.class);
if (ann == null) {
return null;
}
/* Empty String means that we should use name of declared
* value class.
*/
String id = ann.value();
if (id.length() == 0) {
// slight complication; for setters, type
if (!(m instanceof AnnotatedMethod)) {
return m.getRawType().getName();
}
AnnotatedMethod am = (AnnotatedMethod) m;
if (am.getParameterCount() == 0) {
return m.getRawType().getName();
}
return am.getRawParameterType(0).getName();
}
return id;
}
@Override
public Class>[] findViews(Annotated a)
{
JsonView ann = _findAnnotation(a, JsonView.class);
return (ann == null) ? null : ann.value();
}
@Override // since 2.7
public AnnotatedMethod resolveSetterConflict(MapperConfig> config,
AnnotatedMethod setter1, AnnotatedMethod setter2)
{
Class> cls1 = setter1.getRawParameterType(0);
Class> cls2 = setter2.getRawParameterType(0);
// First: prefer primitives over non-primitives
// 11-Dec-2015, tatu: TODO, perhaps consider wrappers for primitives too?
if (cls1.isPrimitive()) {
if (!cls2.isPrimitive()) {
return setter1;
}
} else if (cls2.isPrimitive()) {
return setter2;
}
if (cls1 == String.class) {
if (cls2 != String.class) {
return setter1;
}
} else if (cls2 == String.class) {
return setter2;
}
return null;
}
/*
/**********************************************************
/* Annotations for Polymorphic Type handling
/**********************************************************
*/
@Override
public TypeResolverBuilder> findTypeResolver(MapperConfig> config,
AnnotatedClass ac, JavaType baseType)
{
return _findTypeResolver(config, ac, baseType);
}
@Override
public TypeResolverBuilder> findPropertyTypeResolver(MapperConfig> config,
AnnotatedMember am, JavaType baseType)
{
/* As per definition of @JsonTypeInfo, should only apply to contents of container
* (collection, map) types, not container types themselves:
*/
// 17-Apr-2016, tatu: For 2.7.4 make sure ReferenceType also included
if (baseType.isContainerType() || baseType.isReferenceType()) {
return null;
}
// No per-member type overrides (yet)
return _findTypeResolver(config, am, baseType);
}
@Override
public TypeResolverBuilder> findPropertyContentTypeResolver(MapperConfig> config,
AnnotatedMember am, JavaType containerType)
{
/* First: let's ensure property is a container type: caller should have
* verified but just to be sure
*/
if (containerType.getContentType() == null) {
throw new IllegalArgumentException("Must call method with a container or reference type (got "+containerType+")");
}
return _findTypeResolver(config, am, containerType);
}
@Override
public List findSubtypes(Annotated a)
{
JsonSubTypes t = _findAnnotation(a, JsonSubTypes.class);
if (t == null) return null;
JsonSubTypes.Type[] types = t.value();
ArrayList result = new ArrayList(types.length);
for (JsonSubTypes.Type type : types) {
result.add(new NamedType(type.value(), type.name()));
}
return result;
}
@Override
public String findTypeName(AnnotatedClass ac)
{
JsonTypeName tn = _findAnnotation(ac, JsonTypeName.class);
return (tn == null) ? null : tn.value();
}
@Override
public Boolean isTypeId(AnnotatedMember member) {
return _hasAnnotation(member, JsonTypeId.class);
}
/*
/**********************************************************
/* Annotations for Object Id handling
/**********************************************************
*/
@Override
public ObjectIdInfo findObjectIdInfo(Annotated ann) {
JsonIdentityInfo info = _findAnnotation(ann, JsonIdentityInfo.class);
if (info == null || info.generator() == ObjectIdGenerators.None.class) {
return null;
}
// In future may need to allow passing namespace?
PropertyName name = PropertyName.construct(info.property());
return new ObjectIdInfo(name, info.scope(), info.generator(), info.resolver());
}
@Override
public ObjectIdInfo findObjectReferenceInfo(Annotated ann, ObjectIdInfo objectIdInfo) {
JsonIdentityReference ref = _findAnnotation(ann, JsonIdentityReference.class);
if (ref == null) {
return objectIdInfo;
}
if (objectIdInfo == null) {
objectIdInfo = ObjectIdInfo.empty();
}
return objectIdInfo.withAlwaysAsId(ref.alwaysAsId());
}
/*
/**********************************************************
/* Serialization: general annotations
/**********************************************************
*/
@Override
public Object findSerializer(Annotated a)
{
JsonSerialize ann = _findAnnotation(a, JsonSerialize.class);
if (ann != null) {
@SuppressWarnings("rawtypes")
Class extends JsonSerializer> serClass = ann.using();
if (serClass != JsonSerializer.None.class) {
return serClass;
}
}
/* 18-Oct-2010, tatu: [JACKSON-351] @JsonRawValue handled just here, for now;
* if we need to get raw indicator from other sources need to add
* separate accessor within {@link AnnotationIntrospector} interface.
*/
JsonRawValue annRaw = _findAnnotation(a, JsonRawValue.class);
if ((annRaw != null) && annRaw.value()) {
// let's construct instance with nominal type:
Class> cls = a.getRawType();
return new RawSerializer