Class BeanContext
This class servers multiple purposes:
-
Provides the ability to wrap beans inside
Mapinterfaces. -
Serves as a repository for metadata on POJOs, such as associated
@Beanannotations,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 BeanContext.create() and BeanContext.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 BeanContext that share the same BeanContext class cannot be overridden on the session.
Bean Sessions
Whereas BeanSession 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.
BeanContext configuration properties
Some settings (e.g. BeanContext.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. BeanContext.Builder.beanFieldVisibility(Visibility)) are used to determine what kinds of properties are
detected on beans.
Some settings (e.g. BeanContext.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...
BeanSession.toBeanMap()- Wraps an existing bean inside aMapwrapper.BeanSession.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 BeanContextDefault config.static final BeanSessionDefault reusable unmodifiable session.static final BeanContextDefault config.Fields inherited from class org.apache.juneau.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 BeanContext.Buildercreate()Creates a new builder for this object.Create a session builder based on the properties defined on this context.final VisibilityMinimum bean class visibility.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.protected WriterSerializerReturns the serializer to use for serializing beans when using theBeanSession.convertToType(Object, Class)and related methods.final StringBean type property name.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>Shortcut for callinggetClassMeta(o.getClass()).Class metadata cache.final LocaleLocale.final MediaTypeMedia type.final TimeZoneTime zone.protected final HashKeyHash key.protected final LocaleLocale.protected final MediaTypeMedia type.Bean class exclusions.Bean package exclusions.final PropertyNamerBean property namer.Returns a session to use for this context.final List<ObjectSwap<?,?>> getSwaps()Java object swaps.protected final TimeZoneTime zone.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 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.protected final booleanisNotABean(ClassInfo ci) Determines whether the specified class is ignored as a bean class based on the various exclusion parameters specified on this context class.final booleanSort bean properties.final booleanUse enum names.final booleanUse interface proxies.final booleanUse Java Introspector.<T> BeanMap<T>newBeanMap(Class<T> c) object()Returns a reusableClassMetarepresentation for the classObject .Returns the properties on this bean as a map for debugging.protected final <T> ClassMeta<T>resolveClassMeta(AnnotationInfo<Beanp> p, ClassInfo ci, TypeVariables typeVarImpls) Used for determining the class type on a method or field where a@Beanpannotation may be present.string()Returns a reusableClassMetarepresentation for the classString .<T> BeanMap<T>toBeanMap(T object) Methods inherited from class org.apache.juneau.Context
createBuilder, getAnnotationProvider, init, isDebug, toString
-
Field Details
-
DEFAULT
Default config. All default settings. -
DEFAULT_SORTED
Default config. All default settings except sort bean properties. -
DEFAULT_SESSION
Default reusable unmodifiable session. Can be used to avoid overhead of creating a session (for creating BeanMaps for example).
-
-
Constructor Details
-
BeanContext
Constructor.- Parameters:
builder- The builder for this object.
-
-
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.type- The class type to convert the value to.- 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:
-
getBeanDictionary
Bean dictionary.- Returns:
- The list of classes that make up the bean dictionary in this bean context.
Nevernull .
List is unmodifiable. - See Also:
-
getBeanFieldVisibility
Minimum bean field visibility.- Returns:
- Only look for bean fields with this specified minimum visibility.
- See Also:
-
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,GenericArrayTypeargs- 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.
-
getClassMetaForObject
Shortcut for callinggetClassMeta(o.getClass()).- Type Parameters:
T- The class of the object being passed in.- Parameters:
o- The class 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.
- See Also:
-
getDefaultTimeZone
Time zone.- Returns:
- The default timezone for serializer and parser sessions.
- 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:
-
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:
-
isSortProperties
Sort bean properties.- Returns:
true if all bean properties will be serialized and access in alphabetical order.- See Also:
-
isUseEnumNames
Use enum names.- Returns:
true if enums are always serialized by name, not usingObject.toString().- 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 = BeanContext.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.
- 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 = BeanContext.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 theBeanSession.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.
-
getMediaType
Media type.- Returns:
- The media type.
-
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.
-
isIgnoreTransientFields
Ignore transient fields.- Returns:
true if fields and methods marked as transient should not be ignored.- See Also:
-
isNotABean
Determines whether the specified class is ignored as a bean class based on the various exclusion parameters specified on this context class.- Parameters:
ci- The class info being tested.- Returns:
true if the specified class matches any of the exclusion parameters.
-
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.
-
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<Beanp> p, ClassInfo ci, TypeVariables typeVarImpls) Used for determining the class type on a method or field where a@Beanpannotation 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.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.
-