Class BeanContext
- All Implemented Interfaces:
AnnotationProvider
This class servers multiple purposes:
-
Provides the ability to wrap beans inside
Map
interfaces. -
Serves as a repository for metadata on POJOs, such as associated
@Bean
annotations,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 aMap
wrapper.BeanSession.newBeanMap()
- Create a new bean instance wrapped in aMap
wrapper.
Example:
Notes:
- This class is thread safe and reusable.
See Also:
-
Nested Class Summary
-
Field Summary
Modifier and TypeFieldDescriptionstatic final BeanContext
Default config.static final BeanSession
Default reusable unmodifiable session.static final BeanContext
Default config.Fields inherited from class org.apache.juneau.Context
CONTEXT_APPLY_FILTER
Fields inherited from interface org.apache.juneau.AnnotationProvider
DISABLE_ANNOTATION_CACHING
-
Constructor Summary
-
Method Summary
Modifier and TypeMethodDescription_class()
Returns a reusableClassMeta
representation for the classClass .final <T> T
convertToMemberType
(Object outer, Object value, Class<T> type) Same asconvertToType(Object, Class)
, except used for instantiating inner member classes that must be instantiated within another class instance.final <T> T
convertToType
(Object value, Class<T> type) Converts the specified value to the specified class type.final <T> T
convertToType
(Object value, Type type, Type... args) Same asconvertToType(Object, Class)
, but allows for complex data types consisting of collections or maps.copy()
Creates a builder from this context object.static BeanContext.Builder
create()
Creates a new builder for this object.Create a session builder based on the properties defined on this context.final Visibility
Minimum bean class visibility.final Visibility
Minimum bean constructor visibility.Bean dictionary.final Visibility
Minimum bean field visibility.final <T> BeanMeta<T>
getBeanMeta
(Class<T> c) Returns theBeanMeta
class for the specified class.final Visibility
Minimum bean method visibility.protected final BeanRegistry
Returns the lookup table for resolving bean types by name.protected WriterSerializer
Returns the serializer to use for serializing beans when using theBeanSession.convertToType(Object, Class)
and related methods.final String
Bean type property name.final <T> ClassMeta<T>
getClassMeta
(Class<T> type) Construct aClassMeta
wrapper around aClass
object.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())
.final Locale
Locale.final MediaType
Media type.final TimeZone
Time zone.protected final Class<?>[]
Bean class exclusions.final String[]
Bean package exclusions.protected final String[]
Bean package exclusions.final PropertyNamer
Bean property namer.Returns a session to use for this context.final ObjectSwap<?,
?>[] getSwaps()
Java object swaps.final boolean
Returnstrue if the specified bean context shares the same cache as this bean context.boolean
Returnstrue if the specified object is a bean.final boolean
BeanMap.put() returns old property value.final boolean
Beans require no-arg constructors.final boolean
Beans require Serializable interface.final boolean
Beans require setters for getters.final boolean
Beans require at least one property.final boolean
Find fluent setters.final boolean
Ignore invocation errors on getters.final boolean
Ignore invocation errors on setters.final boolean
Silently ignore missing setters.protected final boolean
Ignore transient fields.final boolean
Ignore unknown properties.final boolean
Ignore unknown enum values.final boolean
Ignore unknown properties with null values.protected final boolean
isNotABean
(Class<?> c) Determines whether the specified class is ignored as a bean class based on the various exclusion parameters specified on this context class.final boolean
Sort bean properties.final boolean
Use enum names.final boolean
Use interface proxies.final boolean
Use Java Introspector.<T> BeanMap<T>
newBeanMap
(Class<T> c) object()
Returns a reusableClassMeta
representation for the classObject .protected JsonMap
Returns the properties on this bean as a map for debugging.protected final <T> ClassMeta<T>
Used for determining the class type on a method or field where a@Beanp
annotation may be present.string()
Returns a reusableClassMeta
representation for the classString .<T> BeanMap<T>
toBeanMap
(T object) Methods inherited from class org.apache.juneau.Context
createBuilder, firstAnnotation, firstAnnotation, firstAnnotation, firstAnnotation, firstDeclaredAnnotation, forEachAnnotation, forEachAnnotation, forEachAnnotation, forEachAnnotation, forEachDeclaredAnnotation, hasAnnotation, hasAnnotation, hasAnnotation, hasAnnotation, init, isDebug, lastAnnotation, lastAnnotation, lastAnnotation, lastAnnotation, lastDeclaredAnnotation, 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.
-
copy
Description copied from class:Context
Creates 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:Context
Create 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:
createSession
in classContext
- Returns:
- A new session builder.
-
getSession
Description copied from class:Context
Returns a session to use for this context.Note that subclasses may opt to return a reusable non-modifiable session.
- Overrides:
getSession
in classContext
- Returns:
- A new session object.
-
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.- Returns:
true if the bean contexts have equivalent settings and thus share caches.
-
toBeanMap
Wraps an object inside aBeanMap
object (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. Must not be null.- Returns:
- The wrapped object.
- See Also:
-
newBeanMap
Creates a newBeanMap
object (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.- Returns:
- A new instance of the class.
- See Also:
-
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:
-
convertToMemberType
public final <T> T convertToMemberType(Object outer, Object value, Class<T> type) throws InvalidDataConversionException Same asconvertToType(Object, Class)
, except used for instantiating inner member classes that must be instantiated within another class instance.This is a shortcut for the following code:
createSession().build().convertToMemberType( outer ,value ,type );- Type Parameters:
T
- The class type to convert the value to.- Parameters:
outer
- If class is a member class, this is the instance of the containing class. Should benull if not a member class.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:
-
convertToType
public final <T> T convertToType(Object value, Type type, Type... args) throws InvalidDataConversionException Same asconvertToType(Object, Class)
, but allows for complex data types consisting of collections or maps.This is a shortcut for the following code:
createSession().build().convertToType( value ,type ,args );- Type Parameters:
T
- The class type to convert the value to.- Parameters:
value
- The value to be converted.type
- The target object type.args
- The target object parameter types.- Returns:
- The converted type.
- Throws:
InvalidDataConversionException
- If the specified value cannot be converted to the specified type.- 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:
c
- The class type being tested.- Returns:
true if the specified class matches any of the exclusion parameters.
-
isBean
Returnstrue if the specified object is a bean.- Parameters:
o
- The object to test.- Returns:
true if the specified object is a bean.false if the bean isnull .
-
getBeanMeta
Returns theBeanMeta
class 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.- Returns:
- The
BeanMeta
for the specified class, ornull if the class is not a bean per the settings on this context.
-
getClassMeta
Construct aClassMeta
wrapper around aClass
object. -
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
,Class
,ParameterizedType
,GenericArrayType
args
- The type arguments of the class if it's a collection or map.
Can be any of the following:ClassMeta
,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.- Returns:
- The ClassMeta object, or
null ifo
isnull .
-
resolveClassMeta
protected final <T> ClassMeta<T> resolveClassMeta(Beanp p, Type t, Map<Class<?>, Class<?>[]> typeVarImpls) Used for determining the class type on a method or field where a@Beanp
annotation may be present.- Type Parameters:
T
- The class type we're wrapping.- Parameters:
p
- The property annotation on the type if there is one.t
- The type.typeVarImpls
- Contains known resolved type parameters on the specified class so that we can resultParameterizedTypes
andTypeVariables
. Can benull if the information is not known.- Returns:
- The new
ClassMeta
object wrapped around theType
object.
-
object
Returns a reusableClassMeta
representation 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
ClassMeta
object associated with theObject class.
-
string
Returns a reusableClassMeta
representation 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
ClassMeta
object associated with theString class.
-
_class
Returns a reusableClassMeta
representation for the classClass .This
ClassMeta is often used to represent key types in maps.This method is identical to calling
getClassMeta(Class.
but uses a cached copy to avoid a hashmap lookup.class )- Returns:
- The
ClassMeta
object associated with theString class.
-
getBeanRegistry
Returns the lookup table for resolving bean types by name.- Returns:
- The lookup table for resolving bean types by name.
-
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.
- See Also:
-
getBeanFieldVisibility
Minimum bean field visibility.- Returns:
- Only look for bean fields with this specified minimum visibility.
- See Also:
-
isBeanMapPutReturnsOldValue
BeanMap.put() returns old property value.- Returns:
true if theBeanMap.put()
method will return old property values.
Otherwise, it returnsnull .- See Also:
-
getBeanMethodVisibility
Minimum bean method visibility.- Returns:
- Only look for bean methods with this specified minimum visibility.
- 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 theSerializable
interface 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:
-
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:
-
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:
-
isIgnoreTransientFields
Ignore transient fields.- Returns:
true if fields and methods marked as transient should not be ignored.- See Also:
-
isIgnoreUnknownBeanProperties
Ignore unknown properties.- Returns:
true if trying to set a value on a non-existent bean property is silently ignored.
Otherwise, aRuntimeException
is 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:
-
getNotBeanClasses
Bean class exclusions.- Returns:
- The list of classes that are explicitly not beans.
- See Also:
-
getNotBeanPackagesNames
Bean package exclusions.- Returns:
- The list of fully-qualified package names to exclude from being classified as beans.
- See Also:
-
getNotBeanPackagesPrefixes
Bean package exclusions.- Returns:
- The list of package name prefixes to exclude from being classified as beans.
- See Also:
-
getSwaps
Java object swaps.- Returns:
- The list POJO swaps defined.
- See Also:
-
getPropertyNamer
Bean property namer.- Returns:
- The interface used to calculate bean property names.
- 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 anInvocationHandler
if 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:
-
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:
-
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.
-
properties
Description copied from class:Context
Returns the properties on this bean as a map for debugging.- Overrides:
properties
in classContext
- Returns:
- The properties on this bean as a map for debugging.
-