A
DynaBean
is a Java object that supports properties whose names and data types, as well as values, may be dynamically modified. To the maximum degree feasible, other components of the BeanUtils package will recognize such beans and treat them as standard JavaBeans for the purpose of retrieving and setting property values.
Another difference compared to an ordinary JavaBean is that we don’t have to provide getters and setter for the properties.
The properties of a DynaBean is set in a DynaClass, so the best way of creating a DynaBean is to create a DynaClass with the appropriate properties and then call newInstance on the class to get the DynaBean instance. A DynaClass is a simulation of the functionality of java.lang.Class for classes implementing the DynaBean interface.DynaBean instances that share the same DynaClass all have the same set of available properties, along with any associated data types, read-only states, and write-only states.
The Beanutil package provides interfaces for DynaBean and DynaClass which may be implemented in your custom class. However, it also provides classes with minimum implementation of these interfaces. These classes are named
BasicDynaBean and BasicDynaClass.
如果JavaBean的属性和属性个数必须在runtime才能确定,你可以使用DynaBean动态创建JavaBean而无需定义一个javabean class.
例如我要统计所有服务器节点的某些状态到一个Bean中,但是生产环境中节点个数是在变动的(一直在增加),怎样避免定义一个JavaBean其属性个数不会timed-out呢?我使用DynaBean.
package
com
.
javadb
.
apachecommons
;
import
org
.
apache
.
commons
.
beanutils
.
BasicDynaClass
;
import
org
.
apache
.
commons
.
beanutils
.
DynaBean
;
import
org
.
apache
.
commons
.
beanutils
.
DynaClass
;
import
org
.
apache
.
commons
.
beanutils
.
DynaProperty
;
/**
*
* @author www.javadb.com
*/
public
class
DynaBeanExample
{
private
final
String
NR_OF_WHEELS
=
"numberOfWheels"
;
private
void
runExample
(
)
{
DynaClass
dynaClass
=
new
BasicDynaClass
(
"Car"
,
null
,
new
DynaProperty
[
]
{
new
DynaProperty
(
NR_OF_WHEELS
,
Integer
.
TYPE
)
}
)
;
try
{
DynaBean
car
=
dynaClass
.
newInstance
(
)
;
car
.
set
(
NR_OF_WHEELS
,
4
)
;
System
.
out
.
println
(
"Number of wheels: "
+
car
.
get
(
NR_OF_WHEELS
)
)
;
System
.
out
.
println
(
"DynaBean is instance of DynaClass: "
+
car
.
getDynaClass
(
)
.
getName
(
)
)
;
}
catch
(
IllegalAccessException | InstantiationException
ex
)
{
System
.
err
.
println
(
ex
.
getMessage
(
)
)
;
}
}
/**
* @param args the command line arguments
*/
public
static
void
main
(
String
[
]
args
)
{
DynaBeanExample
ac
=
new
DynaBeanExample
(
)
;
ac
.
runExample
(
)
;
}
}