Class BeanMap<T>
- Type Parameters:
T- Specifies the type of object that this map encapsulates.
- Direct Known Subclasses:
DelegateBeanMap
Description
A wrapper that wraps Java bean instances inside of aMap interface that allows properties on the wrapped
object can be accessed using the get() and put() methods.
Create instances through the bean API. For the bean-modeling-only path use of(Object) or
of(Object, BeanMeta); the marshalling layer's MarshallingSession#toBeanMap(Object)
additionally wires a BeanSession into the resulting map for session-aware behavior.
Bean property order
The order of the properties returned by thekeySet() and entrySet()
methods is as follows:
-
If the
@BeanTypeannotation specifies an explicit property list viaproperties()(or its synonymp()), the order matches the annotation. -
Otherwise, if
@BeanType(unsorted=true)is set on the class, orBeanConfigContext.isUnsortedProperties()is enabled on the session, properties are returned in their natural reflection order. - Otherwise, properties are returned in alphabetical order.
POJO swaps
IfObjectSwap transforms are defined on the class types of the properties of this bean or the bean properties
themselves, the get(Object) and put(String, Object) methods will automatically transform the
property value to and from the serialized form.
Thread safety
Instances are not thread-safe. This type is mutable (wrapped bean reference, property caches, and optional session pointer) and does not perform internal synchronization.-
Nested Class Summary
Nested classes/interfaces inherited from class java.util.AbstractMap
AbstractMap.SimpleEntry<K extends Object,V extends Object>, AbstractMap.SimpleImmutableEntry<K extends Object, V extends Object> -
Field Summary
FieldsModifier and TypeFieldDescriptionTemporary holding cache for bean properties of array types when the add() method is being used.protected TThe wrapped object.The BeanMeta associated with the class of the object.Temporary holding cache for beans with read-only properties. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidAdd a value to a collection or array property.booleancontainsKey(Object property) entrySet()Returns all the properties associated with the bean.booleanCompares the specified object with this map for equality.forEachProperty(Predicate<BeanPropertyMeta> filter, Consumer<BeanPropertyMeta> action) Performs an action on each property in this bean map.forEachValue(Predicate<Object> valueFilter, BeanPropertyConsumer action) Invokes all the getters on this bean and consumes the results.Gets a property on the bean.<T2> T2Same asget(Object)but casts the value to the specific type.getBean()Returns the wrapped bean object.getBean(boolean create) Returns the wrapped bean object.Returns theBeanInfoof the wrapped bean.final BeanSessionReturns the bean session that created this bean map.getMeta()Returns the metadata associated with this bean map.Returns the@BeanProp(required=true)properties that have not been written to this map.protected Collection<BeanPropertyMeta>Returns a simple collection of properties for this bean map.getProperties(String... fields) Extracts the specified field values from this bean and returns it as a simple Map.getProperty(String propertyName) Returns the specified property on this bean map.getPropertyMeta(String propertyName) Returns the metadata on the specified property.Same asget(Object)except bypasses anyObjectSwapassociated with the bean property orBeanFilterassociated with the bean class.inthashCode()Returns the hash code value for this map.protected booleanisInActiveView(BeanPropertyMeta pMeta) Returnstrue if the property is visible under the active view on this bean map's session.keySet()Returns the names of all properties associated with the bean.Convenience method for loading this map with the contents of the specified map.static <T> BeanMap<T>of(T bean) Convenience method for wrapping a bean inside aBeanMap.static <T> BeanMap<T>Sets a property on the bean.Given a string containing variables of the form"{property}" , replaces those variables with property values in this bean.voidsetBeanSession(BeanSession value) Wires this bean map to aBeanSession.Methods inherited from class java.util.AbstractMap
clear, clone, containsValue, isEmpty, putAll, remove, size, toString, valuesMethods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, wait, wait, waitMethods inherited from interface java.util.Map
compute, computeIfAbsent, computeIfPresent, forEach, getOrDefault, merge, putIfAbsent, remove, replace, replace, replaceAll
-
Field Details
-
bean
The wrapped object. -
propertyCache
Temporary holding cache for beans with read-only properties. Normally null. -
arrayPropertyCache
Temporary holding cache for bean properties of array types when the add() method is being used. -
meta
The BeanMeta associated with the class of the object.
-
-
Constructor Details
-
BeanMap
Constructor.Bean-modeling-only constructor. Does not carry a
BeanSessionreference. The marshalling layer wires the session in viasetBeanSession(BeanSession)immediately after construction.- Parameters:
bean- The bean to wrap inside this map. Can benull for a read-only bean whose properties are supplied later and instantiated viagetBean().meta- The metadata associated with the bean class. Must not benull .
-
-
Method Details
-
of
Convenience method for wrapping a bean inside aBeanMap.- Type Parameters:
T- The bean type.- Parameters:
bean- The bean being wrapped. Must not benull (its runtime class is used to build the metadata).- Returns:
- A new
BeanMapinstance wrapping the bean.
-
of
Convenience method for wrapping a bean inside aBeanMapusing a pre-builtBeanMeta.This is the bean-modeling entry point — it builds a
BeanMapwithout going through a marshalling session, paired with aBeanMetatypically produced byBeanMeta.of(Class, BeanConfigContext). No marshalling session is attached. -
getMissingRequiredProperties
Returns the@BeanProp(required=true)properties that have not been written to this map.A property counts as written once
put(String, Object)(or a collectionadd) has been called for it, even with anull value. Parsers call this once per bean, before the bean is constructed.Example:
// MyBean has @BeanProp(required=true) on 'name' and 'zip'. BeanMap<MyBean>m =session .newBeanMap(MyBean.class );m .put("name" ,null );// [zip] List<String>missing =m .getMissingRequiredProperties();- Returns:
- The missing required property names, in property order. Empty (never
null ) if none.
-
setBeanSession
Wires this bean map to aBeanSession.Called by marshalling-side construction paths (for example,
MarshallingSession#toBeanMap(Object)) to wire in the session used by session-aware operations (type conversion, child collection construction, and parser/serializer-backed conversions) after bean-modeling construction.- Parameters:
value- The bean session that produced this bean map. Typically a marshalling-session implementation. Can benull to detach the session.
-
add
Add a value to a collection or array property.As a general rule, adding to arrays is not recommended since the array must be recreate each time this method is called.
- Parameters:
property- Property name or child-element name (if@Xml(childName)is specified).value- The value to add to the collection or array. Can benull .
-
containsKey
- Specified by:
containsKeyin interfaceMap<String,Object> - Overrides:
containsKeyin classAbstractMap<String,Object>
-
entrySet
Returns all the properties associated with the bean. -
forEachProperty
public BeanMap<T> forEachProperty(Predicate<BeanPropertyMeta> filter, Consumer<BeanPropertyMeta> action) Performs an action on each property in this bean map.If a
BeanSessionis attached and has an active view, only properties that are visible under that view (as determined byBeanSession.isPropertyInActiveView(BeanPropertyMeta)) are visited.- Parameters:
filter- The filter to apply to properties.action- The action.- Returns:
- This object.
-
isInActiveView
Returnstrue if the property is visible under the active view on this bean map's session.When no session is attached, or no active view is set, all properties are visible.
- Parameters:
pMeta- The property to test.- Returns:
true if the property is in-view.
-
forEachValue
Invokes all the getters on this bean and consumes the results.- Parameters:
valueFilter- Filter to apply to value before applying action.action- The action to perform.- Returns:
- The list of all bean property values.
-
get
Gets a property on the bean.If an
ObjectSwap-style transform is associated with this bean property or bean property type class, then this method will return the transformed value. For example, if the bean property type class is aDateand the bean property has theDateFormat.ISO_INSTANTsetting associated with it through the@Swap(value)annotation, this method will return a String containing an ISO8601 date-time string value.Example:
// Construct a bean with a 'birthDate' Date field Personperson =new Person();person .setBirthDate(new Date(1, 2, 3, 4, 5, 6));// Create a marshalling context and add the ISO8601 date-time swap MarshallingContextmarshallingContext = MarshallingContext.create ().dateFormat(DateFormat.ISO_INSTANT ).build();// Wrap our bean in a bean map BeanMap<Person>beanMap =marshallingContext .toBeanMap(person );// Get the field as a string (i.e. "'1901-03-03T04:05:06-5000'") StringbirthDate =beanMap .get("birthDate" );- Specified by:
getin interfaceMap<String,Object> - Overrides:
getin classAbstractMap<String,Object> - Parameters:
property- The name of the property to get.- Returns:
- The property value.
- Throws:
RuntimeException- if any of the following occur.- BeanMapEntry does not exist on the underlying object.
- Security settings prevent access to the underlying object getter method.
- An exception occurred inside the getter method.
-
get
Same asget(Object)but casts the value to the specific type.- Type Parameters:
T2- The type to cast to.- Parameters:
property- The name of the property to get.c- The type to cast to.- Returns:
- The property value.
- Throws:
RuntimeException- if any of the following occur.- BeanMapEntry does not exist on the underlying object.
- Security settings prevent access to the underlying object getter method.
- An exception occurred inside the getter method.
ClassCastException- if property is not the specified type.
-
getBean
Returns the wrapped bean object.Triggers bean creation if bean has read-only properties set through a constructor defined by the
@BeanCtorannotation.The post-creation Optional<X> initialization step (which seeds null
Optionalproperties withBeanInfo.getOptionalDefault()) is skipped for properties built via the bean-modeling-only path (BeanMeta.of(Class, BeanConfigContext)) because per-property type metadata is unavailable; those properties are left untouched and anyOptional-typed field stays at its constructor-assigned value.- Returns:
- The inner bean object.
-
getBean
Returns the wrapped bean object.If
create isfalse , then this method may returnnull if the bean has read-only properties set through a constructor defined by the@BeanCtorannotation.This method does NOT always return the bean in it's final state. Array properties temporary stored as ArrayLists are not finalized until the
getBean()method is called.- Parameters:
create- If bean hasn't been instantiated yet, then instantiate it.- Returns:
- The inner bean object.
-
getBeanSession
Returns the bean session that created this bean map.The returned value is the bean-modeling SPI seam. Marshalling-side callers needing the concrete marshalling-session implementation can cast — every session wired in via
setBeanSession(BeanSession)on the marshalling-side path is currently aMarshallingSession.- Returns:
- The bean session that created this bean map.
-
getBeanInfo
Returns theBeanInfoof the wrapped bean.- Specified by:
getBeanInfoin interfaceDelegate<T>- Returns:
- The class type of the wrapped bean.
-
getMeta
Returns the metadata associated with this bean map.- Returns:
- The metadata associated with this bean map.
-
getProperties
Extracts the specified field values from this bean and returns it as a simple Map.The returned map is a live view over this bean map: each entry's
getValuereads through toBeanMap.getandsetValuewrites through toBeanMap.put. Unknownfields(keys not present in this bean map) are silently skipped.- Parameters:
fields- The fields to extract.- Returns:
- A new map with fields as key-value pairs.
Note that modifying the values in this map will also modify the underlying bean.
-
getProperty
Returns the specified property on this bean map.Allows you to get and set an individual property on a bean without having a handle to the bean itself by using the
BeanMapEntry.getValue()andBeanMapEntry.setValue(Object)methods.This method can also be used to get metadata on a property by calling the
BeanMapEntry.getMeta()method.- Parameters:
propertyName- The name of the property to look up.- Returns:
- The bean property, or null if the bean has no such property.
-
getPropertyMeta
Returns the metadata on the specified property.Returns
null if the property does not exist on the bean or if the property exists but is excluded by the current active view. The latter allows the caller (e.g.put(String, Object)) to route out-of-view input through the existing unknown/ignored-property path governed byBeanConfigContext.isIgnoreUnknownBeanProperties().- Parameters:
propertyName- The name of the bean property.- Returns:
- Metadata on the specified property, or
null if that property does not exist or is out of view.
-
getRaw
Same asget(Object)except bypasses anyObjectSwapassociated with the bean property orBeanFilterassociated with the bean class.- Parameters:
property- The name of the property to get.- Returns:
- The raw property value.
-
keySet
Returns the names of all properties associated with the bean.The returned set is unmodifiable.
-
load
Convenience method for loading this map with the contents of the specified map.Identical to
AbstractMap.putAll(Map)except as a fluent-style method.- Parameters:
entries- The map containing the entries to add to this map.- Returns:
- This object.
-
put
Sets a property on the bean.If there is a
ObjectSwapassociated with this bean property or bean property type class, then you must pass in a transformed value. For example, if the bean property type class is aDateand the bean property has theDateFormat.ISO_INSTANTsetting associated with it through the@Swap(value)annotation, the value being passed in must be a String containing an ISO8601 date-time string value.Example:
// Construct a bean with a 'birthDate' Date field Personperson =new Person();// Create a marshalling context and add the ISO8601 date-time swap MarshallingContextmarshallingContext = MarshallingContext.create ().dateFormat(DateFormat.ISO_INSTANT ).build();// Wrap our bean in a bean map BeanMap<Person>beanMap =marshallingContext .toBeanMap(person );// Set the field beanMap .put("birthDate" ,"'1901-03-03T04:05:06-5000'" );- Specified by:
putin interfaceMap<String,Object> - Overrides:
putin classAbstractMap<String,Object> - Parameters:
property- The name of the property to set.value- The value to set the property to. Can benull to set the property tonull .- Returns:
- If the
beanMapPutReturnsOldValuesetting istrue on the session's bean configuration, then the old value of the property is returned. Otherwise, this method always returnsnull . - Throws:
RuntimeException- if any of the following occur.- BeanMapEntry does not exist on the underlying object.
- Security settings prevent access to the underlying object setter method.
- An exception occurred inside the setter method.
-
resolveVars
Given a string containing variables of the form"{property}" , replaces those variables with property values in this bean.- Parameters:
s- The string containing variables.- Returns:
- A new string with variables replaced, or the same string if no variables were found.
-
getProperties
Returns a simple collection of properties for this bean map.- Returns:
- A simple collection of properties for this bean map.
-
equals
Compares the specified object with this map for equality.Returns
true if the given object is also a map and the two maps represent the same mappings. More formally, two mapsm1 andm2 represent the same mappings ifm1.entrySet().equals(m2.entrySet()) .This implementation compares the entry sets of the two maps.
-
hashCode
Returns the hash code value for this map.The hash code of a map is defined to be the sum of the hash codes of each entry in the map's
entrySet() view. This ensures thatm1.equals(m2) implies thatm1.hashCode()==m2.hashCode() for any two mapsm1 andm2 , as required by the general contract ofObject.hashCode().This implementation computes the hash code from the entry set.
-