8.9. Enhancing DynaBeans
The BasicDynaClass and BasicDynaBean classes have certain limitations. DynaBeans may not have methods, and there is no provision for a dynamic bean to extend another the way Java classes can. It is also not possible to dynamically add new properties.Despite these restrictions, dynamic beans can be very useful in certain applications. Notably, dynamic beans work extremely well with databases. It is often extremely convenient to represent the result of a query as an array of beans that have a property for each column. This can be done statically for beans representing tables, but it is very common for a query to return fields from multiple tables. It would not make sense to define a separate Java class for each query that might be executed throughout a program. Nor does a Map provide an adequate solution, because type information is important in database applications. DynaBeans fit the bill perfectly.In cases where some additional functionality is needed it is possible to create custom dynamic beans. This can be done by writing classes that extend BasicDynaBean and BasicDynaClass, or by creating classes that implement the DynaBean or DynaClass interfaces. One possible use for this would be to equip a DynaBean with a property that is defined remotely or that continuously updates. This can be done by extending BasicDynaBean with regular bean properties, as in
To use this class it is just necessary to specify DateDynaBean.class as the second argument when creating the DynaClass. Any DynaBeans thus defined will automatically have the date property.
public class DateDynaBean extends BasicDynaBean {
public Date getDate() {return new Date();}
public Object get(String name) {
if(name.equals("date")) {
return getDate();
}
return super.get(name);
}
}