Class MarshallingContext
- All Implemented Interfaces:
BeanTypeResolver,ConversionFinder
This class servers multiple purposes:
-
Provides the ability to wrap beans inside
Mapinterfaces. -
Serves as a repository for metadata on POJOs, such as associated
@Marshalledannotations,PropertyNamers, etc... which are used to tailor how POJOs are serialized and parsed.
All serializers and parsers use this context so that they can handle POJOs using a common framework.
Bean Contexts
Bean contexts are created through the MarshallingContext.create() and MarshallingContext.Builder.build() methods.
These context objects are read-only, reusable, and thread-safe.
Each bean context maintains a cache of ClassMeta objects that describe information about classes encountered.
These MarshallingContext that share the same MarshallingContext class cannot be overridden on the session.
Bean Sessions
Whereas MarshallingSession objects are ephemeral and not thread-safe.
They are meant to be used as quickly-constructed scratchpads for creating bean maps.
BeanMap objects can only be created through the session.
MarshallingContext configuration properties
Some settings (e.g. MarshallingContext.Builder.beansRequireDefaultConstructor()) are used to differentiate between bean
and non-bean classes.
Attempting to create a bean map around one of these objects will throw a BeanRuntimeException.
The purpose for this behavior is so that the serializers can identify these non-bean classes and convert them to
plain strings using the Object.toString() method.
Some settings (e.g. MarshallingContext.Builder.beanFieldVisibility(Visibility)) are used to determine what kinds of properties are
detected on beans.
Some settings (e.g. MarshallingContext.Builder.beanMapPutReturnsOldValue()) change the runtime behavior of bean maps.
Example:
Bean Maps
BeanMaps are wrappers around Java beans that allow properties to be retrieved and
set using the common Map.put(Object,Object) and Map.get(Object) methods.
Bean maps are created in two ways...
MarshallingSession.toBeanMap()- Wraps an existing bean inside aMapwrapper.MarshallingSession.newBeanMap()- Create a new bean instance wrapped in aMapwrapper.
Example:
Notes:
- This class is thread safe and reusable.
See Also:
-
Nested Class Summary
Nested Classes -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final MarshallingContextDefault config.static final MarshallingSessionDefault reusable unmodifiable session.Fields inherited from class org.apache.juneau.marshall.Context
CONTEXT_APPLY_FILTER -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionfinal <T> TconvertToType(Object value, Class<T> type) Converts the specified value to the specified class type.copy()Creates a builder from this context object.static MarshallingContext.Buildercreate()Creates a new builder for this object.Create a session builder based on the properties defined on this context.Conversion<?,?> findConversion(Class<?> inType, Class<?> outType) ImplementsConversionFinderto provide all MarshallingContext-specific type conversions that cannot be expressed inBasicConverter(which has no dependency onjuneau-marshall).final StringThe default active view for sessions created from this context.final VisibilityMinimum bean class visibility.final BeanConfigContextReturns theBeanConfigContextsnapshot for this marshalling context.final VisibilityMinimum bean constructor visibility.Bean dictionary.final VisibilityMinimum bean field visibility.final <T> BeanMeta<T>getBeanMeta(Class<T> c) Returns theBeanMetaclass for the specified class.final VisibilityMinimum bean method visibility.protected final BeanRegistryReturns the lookup table for resolving bean types by name.final BeanStoreThe bean store used for factory-based instantiation.protected WriterSerializerReturns the serializer to use for serializing beans when using theMarshallingSession.convertToType(Object, Class)and related methods.final StringBean type property name.final BigNumberFormatBig-number wire format.final BinaryFormatBinary wire format.final BitSetFormatBitSet wire format.final BooleanFormatBoolean wire format.final CalendarFormatCalendar wire format.final ClassFormatClass wire format.final ClassLoaderSession classloader.final <T> ClassMeta<T>getClassMeta(Class<T> type) Construct aClassMetawrapper around aClassobject.final <T> ClassMeta<T>getClassMeta(Type type, Type... args) Used to resolveClassMetas of typeCollection andMap that haveClassMeta values that themselves could be collections or maps.final <T> ClassMeta<T>Returns theClassMetafor the object's class, unwrapping recognized proxies first.Class metadata cache.final ConfigurableConverterReturns the converter for this context.final CurrencyFormatCurrency wire format.final DateFormatDate wire format.final LocaleLocale.final MediaTypeMedia type.final TimeZoneTime zone.final DurationFormatDuration wire format.final EnumFormatEnum wire format.final FloatFormatFloat / Double non-finite wire format.protected final HashKeyHash key.protected final LocaleLocale.final LocaleFormatLocale wire format.protected final MediaTypeMedia type.Bean class exclusions.Bean package exclusions.final PeriodFormatPeriod wire format.final PropertyNamerBean property namer.Returns a session to use for this context.final List<ObjectSwap<?,?>> getSwaps()Java object swaps.final TemporalFormatTemporal wire format.protected final TimeZoneTime zone.final TimeZoneFormatTime-zone wire format.final UuidFormatUUID wire format.final booleanReturnstrue if the specified bean context shares the same cache as this bean context.final booleanBeanMap.put() returns old property value.final booleanBeans require no-arg constructors.final booleanBeans require Serializable interface.final booleanBeans require setters for getters.final booleanBeans require at least one property.final booleanDefault-view-inclusion policy.final booleanFind fluent setters.final booleanIgnore invocation errors on getters.final booleanIgnore invocation errors on setters.final booleanSilently ignore missing setters.protected final booleanIgnore transient fields.final booleanIgnore unknown properties.final booleanIgnore unknown enum values.final booleanIgnore unknown properties with null values.final booleanReturns whetherRecordbeans use record component order.final booleanReturns whether bean properties are unsorted (i.e. in declaration order rather than alphabetical).final booleanUse interface proxies.final booleanUse Java Introspector.final booleanSchema validation mode.<T> BeanMap<T>newBeanMap(Class<T> c) object()Returns a reusableClassMetarepresentation for the classObject .BeanInfo<?>Returns the type-info forObject.class(used as the fallback element/value type for raw/unparameterized collections and maps).Returns the properties on this bean as a map for debugging.protected final <T> ClassMeta<T>resolveClassMeta(AnnotationInfo<BeanProp> p, ClassInfo ci, TypeVariables typeVarImpls) Used for determining the class type on a method or field where a@BeanPropannotation may be present.BeanInfo<?>resolveType(AnnotationInfo<BeanProp> lastBeanProp, ClassInfo type, TypeVariables typeVarImpls) Resolves the bean-property type-info for a property given its (optional)@BeanPropannotation and Java type.string()Returns a reusableClassMetarepresentation for the classString .<T> BeanMap<T>toBeanMap(T object) Methods inherited from class org.apache.juneau.marshall.Context
createBuilder, getAnnotationProvider, init, isDebug, toStringMethods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods inherited from interface org.apache.juneau.commons.bean.BeanTypeResolver
getAnnotationProvider
-
Field Details
-
DEFAULT
Default config. All default settings. -
DEFAULT_SESSION
Default reusable unmodifiable session. Can be used to avoid overhead of creating a session (for creating BeanMaps for example).
-
-
Constructor Details
-
MarshallingContext
Constructor.- Parameters:
builder- The builder for this object.
Cannot benull .
-
-
Method Details
-
create
Creates a new builder for this object.- Returns:
- A new builder.
-
convertToType
Converts the specified value to the specified class type.This is a shortcut for the following code:
createSession().build().convertToType( value ,type );- Type Parameters:
T- The class type to convert the value to.- Parameters:
value- The value to convert.
Can benull (returnsnull ).type- The class type to convert the value to.
Cannot benull .- Returns:
- The converted value.
- Throws:
InvalidDataConversionException- If the specified value cannot be converted to the specified type.- See Also:
-
copy
Description copied from class:ContextCreates a builder from this context object.Builders are used to define new contexts (e.g. serializers, parsers) based on existing configurations.
-
createSession
Description copied from class:ContextCreate a session builder based on the properties defined on this context.Use this method for creating sessions where you want to override basic settings. Otherwise, use
Context.getSession()directly.- Overrides:
createSessionin classContext- Returns:
- A new session builder.
-
getBeanClassVisibility
Minimum bean class visibility.- Returns:
- Classes are not considered beans unless they meet the minimum visibility requirements.
- See Also:
-
getBeanConstructorVisibility
Minimum bean constructor visibility.- Returns:
- Only look for constructors with this specified minimum visibility.
- See Also:
-
getBeanStore
The bean store used for factory-based instantiation.- Returns:
- The bean store, or
null if none configured. - See Also:
-
getBeanDictionary
Bean dictionary.- Returns:
- The list of classes that make up the bean dictionary in this bean context.
Nevernull .
List is unmodifiable. - See Also:
-
getBeanConfigContext
Returns theBeanConfigContextsnapshot for this marshalling context.The snapshot lifts the bean-modeling subset of this context's settings into a portable POJO that the bean-modeling runtime in
commons.beancan consume without referencing any marshalling-aware types. It is computed lazily on first access and cached for the lifetime of this context.Mutating the returned snapshot's settings (via
BeanConfigContext.copy()and a fresh build) does not affect this marshalling context.- Returns:
- The bean-modeling configuration snapshot. Never
null .
-
getBeanFieldVisibility
Minimum bean field visibility.- Returns:
- Only look for bean fields with this specified minimum visibility.
- See Also:
-
getConverter
Returns the converter for this context.- Returns:
- The converter.
-
findConversion
ImplementsConversionFinderto provide all MarshallingContext-specific type conversions that cannot be expressed inBasicConverter(which has no dependency onjuneau-marshall).Conversions are resolved in this priority order:
- ObjectSwap-based conversions (highest priority)
- Iso8601 date/time formatting and parsing
- Epoch-millis to date/time
- Map/Bean/Collection/Array to String via serializer
- String/CharSequence to Array, Map, Collection via JSON parsing
- Map to Bean and String to Bean via BeanMap
- Calendar/Date specialized copies
- InputStream and Reader construction
- Specified by:
findConversionin interfaceConversionFinder- Parameters:
inType- The input type class.outType- The output type class.- Returns:
- A matching
Conversion, ornullif none applies.
-
getBeanMeta
Returns theBeanMetaclass for the specified class.- Type Parameters:
T- The class type to get the meta-data on.- Parameters:
c- The class to get the meta-data on.
Cannot benull .- Returns:
- The
BeanMetafor the specified class, ornull if the class is not a bean per the settings on this context.
-
getBeanMethodVisibility
Minimum bean method visibility.- Returns:
- Only look for bean methods with this specified minimum visibility.
- See Also:
-
getBeanTypePropertyName
Bean type property name.- Returns:
- The name of the bean property used to store the dictionary name of a bean type so that the parser knows the data type to reconstruct.
- See Also:
-
getClassMeta
Construct aClassMetawrapper around aClassobject. -
getClassMeta
Used to resolveClassMetas of typeCollection andMap that haveClassMeta values that themselves could be collections or maps.Collection meta objects are assumed to be followed by zero or one meta objects indicating the element type.Map meta objects are assumed to be followed by zero or two meta objects indicating the key and value types.The array can be arbitrarily long to indicate arbitrarily complex data structures.
Examples:
getClassMeta(String.- A normal type.class );getClassMeta(List.- A list containing objects.class );getClassMeta(List.- A list containing strings.class , String.class );getClassMeta(LinkedList.- A linked-list containing strings.class , String.class );getClassMeta(LinkedList.- A linked-list containing linked-lists of strings.class , LinkedList.class , String.class );getClassMeta(Map.- A map containing object keys/values.class );getClassMeta(Map.- A map containing string keys/values.class , String.class , String.class );getClassMeta(Map.- A map containing string keys and values of lists containing beans.class , String.class , List.class , MyBean.class );
- Type Parameters:
T- The class to resolve.- Parameters:
type- The class to resolve.
Can be any of the following:ClassMeta,ClassInfo,Class,ParameterizedType,GenericArrayType
Can benull (returnsnull ).args- The type arguments of the class if it's a collection or map.
Can be any of the following:ClassMeta,ClassInfo,Class,ParameterizedType,GenericArrayType
Ignored if the main type is not a map or collection.- Returns:
- The resolved class meta, or
null if the type wasnull .
-
getClassMetaForObject
Returns theClassMetafor the object's class, unwrapping recognized proxies first.Same contract as
MarshallingSession.getClassMetaForObject(Object, ClassMeta):ClassUtils.getProxyFor(Object)if non-null , elseo.getClass(). Used by object-tools and other context callers; parsers do not call this method.- Type Parameters:
T- The class of the object being passed in.- Parameters:
o- The object to find the class type for.
Cannot benull .- Returns:
- The ClassMeta object.
-
getDefaultLocale
Locale.- Returns:
- The default locale for serializer and parser sessions.
- See Also:
-
getDefaultMediaType
Media type.- Returns:
- The default media type value for serializer and parser sessions.
Can benull if no default media type has been configured. - See Also:
-
getDefaultTimeZone
Time zone.- Returns:
- The default timezone for serializer and parser sessions.
Can benull if no default time zone has been configured. - See Also:
-
getNotBeanPackagesNames
Bean package exclusions.- Returns:
- The set of fully-qualified package names to exclude from being classified as beans.
Nevernull .
Set is unmodifiable.
Backed by aLinkedHashSetto preserve insertion order. - See Also:
-
getPropertyNamer
Bean property namer.- Returns:
- The interface used to calculate bean property names.
- See Also:
-
getSession
Description copied from class:ContextReturns a session to use for this context.Note that subclasses may opt to return a reusable non-modifiable session.
- Overrides:
getSessionin classContext- Returns:
- A new session object.
-
getSwaps
Java object swaps.- Returns:
- The list POJO swaps defined.
Nevernull .
List is unmodifiable. - See Also:
-
hasSameCache
Returnstrue if the specified bean context shares the same cache as this bean context.Useful for testing purposes.
- Parameters:
bc- The bean context to compare to.
Cannot benull .- Returns:
true if the bean contexts have equivalent settings and thus share caches.
-
isBeanMapPutReturnsOldValue
BeanMap.put() returns old property value.- Returns:
true if theBeanMap.put()method will return old property values.
Otherwise, it returnsnull .- See Also:
-
isBeansRequireDefaultConstructor
Beans require no-arg constructors.- Returns:
true if a Java class must implement a default no-arg constructor to be considered a bean.
Otherwise, the bean will be serialized as a string using theObject.toString()method.- See Also:
-
isBeansRequireSerializable
Beans require Serializable interface.- Returns:
true if a Java class must implement theSerializableinterface to be considered a bean.
Otherwise, the bean will be serialized as a string using theObject.toString()method.- See Also:
-
isBeansRequireSettersForGetters
Beans require setters for getters.- Returns:
true if only getters that have equivalent setters will be considered as properties on a bean.
Otherwise, they are ignored.- See Also:
-
isBeansRequireSomeProperties
Beans require at least one property.- Returns:
true if a Java class doesn't need to contain at least 1 property to be considered a bean.
Otherwise, the bean is serialized as a string using theObject.toString()method.- See Also:
-
isFindFluentSetters
Find fluent setters.Description:
- Returns:
true if fluent setters are detected on beans.- See Also:
-
isIgnoreInvocationExceptionsOnGetters
Ignore invocation errors on getters.- Returns:
true if errors thrown when calling bean getter methods are silently ignored.- See Also:
-
isIgnoreInvocationExceptionsOnSetters
Ignore invocation errors on setters.- Returns:
true if errors thrown when calling bean setter methods are silently ignored.- See Also:
-
isIgnoreMissingSetters
Silently ignore missing setters.- Returns:
true if trying to set a value on a bean property without a setter should throw aBeanRuntimeException.- See Also:
-
isIgnoreUnknownBeanProperties
Ignore unknown properties.- Returns:
true if trying to set a value on a non-existent bean property is silently ignored.
Otherwise, aRuntimeExceptionis thrown.- See Also:
-
isValidateSchema
Schema validation mode.- Returns:
true if bean property values should be validated against their@Schema-declared constraints during parsing and serialization.- Since:
- 10.0.0
- See Also:
-
isIgnoreUnknownEnumValues
Ignore unknown enum values.- Returns:
true if unknown enum values should be set asnull instead of throwing an exception.- See Also:
-
isIgnoreUnknownNullBeanProperties
Ignore unknown properties with null values.- Returns:
true if trying to set anull value on a non-existent bean property should throw aBeanRuntimeException.- See Also:
-
isUnsortedProperties
Returns whether bean properties are unsorted (i.e. in declaration order rather than alphabetical).- Returns:
true if bean properties are in declaration order;false (the default) means alphabetical order.- See Also:
-
isRecordComponentOrder
Returns whetherRecordbeans use record component order.- Returns:
true if record properties are in component order regardless ofisUnsortedProperties().- See Also:
-
isUseInterfaceProxies
Use interface proxies.- Returns:
true if interfaces will be instantiated as proxy classes through the use of anInvocationHandlerif there is no other way of instantiating them.- See Also:
-
isUseJavaBeanIntrospector
Use Java Introspector.- Returns:
true if the built-in Java bean introspector should be used for bean introspection.- See Also:
-
newBeanMap
Creates a newBeanMapobject (a modifiableMap) of the given class with uninitialized property values.This is a shortcut for the following code:
createSession().build().newBeanMap( _class );Example:
// Construct a new bean map wrapped around a new Person object BeanMap<Person>beanMap = MarshallingContext.DEFAULT .newBeanMap(Person.class );- Type Parameters:
T- The class of the object being wrapped.- Parameters:
c- The name of the class to create a new instance of.
Cannot benull .- Returns:
- A new instance of the class, or
null if the class is not a bean. - See Also:
-
toBeanMap
Wraps an object inside aBeanMapobject (a modifiableMap).This is a shortcut for the following code:
createSession().build().toBeanMap( object );Example:
// Construct a bean map around a bean instance BeanMap<Person>beanMap = MarshallingContext.DEFAULT .toBeanMap(new Person());- Type Parameters:
T- The class of the object being wrapped.- Parameters:
object- The object to wrap in a map interface.
Cannot benull .- Returns:
- The wrapped object.
- See Also:
-
getBeanRegistry
Returns the lookup table for resolving bean types by name.- Returns:
- The lookup table for resolving bean types by name.
-
getBeanToStringSerializer
Returns the serializer to use for serializing beans when using theMarshallingSession.convertToType(Object, Class)and related methods.- Returns:
- The serializer. May be
null if all initialization has occurred.
-
getCmCache
Class metadata cache.- Returns:
- The class metadata cache.
-
getHashKey
Hash key.- Returns:
- The hash key.
-
getLocale
Locale.- Returns:
- The locale.
-
getActiveView
The default active view for sessions created from this context.Returns the view name set via
MarshallingContext.Builder.activeView(String), ornull if no default active view has been configured (all properties visible).- Returns:
- The default active view, or
null . - Since:
- 10.0.0
-
isDefaultViewInclusion
Default-view-inclusion policy.Returns
true (the default) when untagged properties — those carrying noMarshalledProp.view()declaration — are included under every active view. Returnsfalse whenMarshallingContext.Builder.disableDefaultViewInclusion()has been called, in which case untagged properties are excluded when any active view is in effect.- Returns:
true if untagged properties are included under every active view.- Since:
- 10.0.0
-
getMediaType
Media type.- Returns:
- The media type, or
null if no default media type has been configured.
-
getNotBeanClasses
Bean class exclusions.- Returns:
- The list of classes that are explicitly not beans.
Nevernull .
List is unmodifiable. - See Also:
-
getTimeZone
Time zone.- Returns:
- The time zone, or
null if no default time zone has been configured.
-
getDurationFormat
Duration wire format.- Returns:
- The duration wire format.
-
getPeriodFormat
Period wire format.- Returns:
- The period wire format.
-
getCalendarFormat
Calendar wire format.- Returns:
- The calendar wire format.
-
getDateFormat
Date wire format.- Returns:
- The date wire format.
-
getTemporalFormat
Temporal wire format.- Returns:
- The temporal wire format.
-
getTimeZoneFormat
Time-zone wire format.- Returns:
- The time-zone wire format.
-
getLocaleFormat
Locale wire format.- Returns:
- The locale wire format.
-
getBinaryFormat
Binary wire format.- Returns:
- The binary wire format.
-
getEnumFormat
Enum wire format.- Returns:
- The enum wire format.
-
getUuidFormat
UUID wire format.- Returns:
- The UUID wire format.
-
getBitSetFormat
BitSet wire format.- Returns:
- The BitSet wire format.
-
getBigNumberFormat
Big-number wire format.- Returns:
- The big-number wire format.
-
getBooleanFormat
Boolean wire format.- Returns:
- The boolean wire format.
-
getFloatFormat
Float / Double non-finite wire format.- Returns:
- The float wire format.
-
getCurrencyFormat
Currency wire format.- Returns:
- The currency wire format.
-
getClassFormat
Class wire format.- Returns:
- The class wire format.
-
getClassLoader
Session classloader.Returns the classloader explicitly configured via
MarshallingContext.Builder.classLoader(ClassLoader), ornull if none was set (callers should fall back to the thread-context classloader).- Returns:
- The session classloader, or
null if not set.
-
isIgnoreTransientFields
Ignore transient fields.- Returns:
true if fields and methods marked as transient should not be ignored.- See Also:
-
object
Returns a reusableClassMetarepresentation for the classObject .This
ClassMeta is often used to represent "any object type" when an object type is not known.This method is identical to calling
getClassMeta(Object.but uses a cached copy to avoid a hashmap lookup.class )- Returns:
- The
ClassMetaobject associated with theObject class.
-
resolveType
public BeanInfo<?> resolveType(AnnotationInfo<BeanProp> lastBeanProp, ClassInfo type, TypeVariables typeVarImpls) Description copied from interface:BeanTypeResolverResolves the bean-property type-info for a property given its (optional)@BeanPropannotation and Java type.- Specified by:
resolveTypein interfaceBeanTypeResolver- Parameters:
lastBeanProp- The last@BeanPropannotation found on the property's field/getter/setter, ornullif none.type- The Java type of the property as derived from the field/getter/setter signature.typeVarImpls- Resolved type-variable substitutions for the enclosing class.- Returns:
- The resolved type-info, or
nullif no resolution was possible.
-
objectType
Description copied from interface:BeanTypeResolverReturns the type-info forObject.class(used as the fallback element/value type for raw/unparameterized collections and maps).- Specified by:
objectTypein interfaceBeanTypeResolver- Returns:
- Non-
nulltype-info forObject.class.
-
properties
Description copied from class:ContextReturns the properties on this bean as a map for debugging.- Overrides:
propertiesin classContext- Returns:
- The properties on this bean as a map for debugging.
-
resolveClassMeta
protected final <T> ClassMeta<T> resolveClassMeta(AnnotationInfo<BeanProp> p, ClassInfo ci, TypeVariables typeVarImpls) Used for determining the class type on a method or field where a@BeanPropannotation may be present.- Type Parameters:
T- The class type we're wrapping.- Parameters:
p- The property annotation info on the type if there is one.
Can benull (the class type is resolved fromci alone, with no@BeanProp -based narrowing).ci- The class info for the type.typeVarImpls- Contains known resolved type parameters on the specified class so that we can resultParameterizedTypesandTypeVariables. Can benull if the information is not known.- Returns:
- The new
ClassMetaobject wrapped around the type.
-
string
Returns a reusableClassMetarepresentation for the classString .This
ClassMeta is often used to represent key types in maps.This method is identical to calling
getClassMeta(String.but uses a cached copy to avoid a hashmap lookup.class )- Returns:
- The
ClassMetaobject associated with theString class.
-