Wednesday, July 2, 2008

Metawidget and Filtering Properties

Update: the APIs shown in this blog entry have changed slightly in newer releases of Metawidget. Specifically PropertyStyles are now set as object instances, not classes. Please download the latest documentation from

I was recently asked whether Metawidget can filter out properties during its inspection process. You may want to do this if, for example, your business classes all extend a common base class that has framework-specific properties that are not 'real' business model properties.

The answer is yes! Metawidget is very flexible in what it does (and does not) inspect.

Whilst you could roll your own ProperyTypeInspector, the convenience implementation BasePropertyTypeInspector - which all annotation-based inspectors extend - already supports pluggable PropertyStyles. The PropertyStyle interface allows fine-grained control over what is considered a 'property'. We use this for both Groovy support, and also StrutsActionFormPropertyStyle:

public class StrutsActionFormPropertyStyle extends JavaBeanPropertyStyle {

   protected String[] getExcludeNames() {
      return new String[] { "servlet", "servletWrapper", "multipartRequestHandler" };

Here, we can see StrutsActionFormPropertyStyle excludes, for example, the property 'servletWrapper' which is a method defined by the Struts ActionForm base class (ActionForm.getServletWrapper).

We can also exclude based on subtype. From GroovyProperty:

   protected Class[] getExcludeTypes() {
      return new Class[] { Class.class, MetaClass.class };

To filter your own base classes:

Step 1: Define a PropertyStyle

In most cases, it's easiest to extend JavaBeanPropertyStyle (see StrutsActionFormPropertyStyle above)

Step 2: Tell the Inspectors to use the PropertyStyle

If you're using inspector-config.xml:

<propertyTypeInspector xmlns="java:org.metawidget.inspector.propertytype"


If you're setting your Inspector programmatically:

BasePropertyInspectorConfig config = new BasePropertyInspectorConfig();
config.setPropertyStyle( StrutsActionFormPropertyStyle.class );
metawidget.setInspector( new PropertyTypeInspector( config ) );

And that's it!