Skip to main content

Property and interceptors

Posted by forax on January 11, 2007 at 8:10 AM PST

Since my last post,

Cay Horstmann

has recalled that properties are intended for tools
and

Hans Muller
bid up
by saying that property syntax is useless
without a way to define bound properties.

Interceptors and bound properties

What Hans want is some kind of interceptor.
An interceptor is an object or a method that can trap access
to a property. In Java, these objects are implemented
either using java.lang.reflect.Proxy or by
bytecode enhancement using a
VM
agent
or a special classloader.


It is interresting to know that
bean interceptors are already defined in
EJB
3 spec (JSR-220)
.

So for me, instead of trying to re-invent the wheel, we could
perhaps transpose the concept of server side interceptors
in Swing world.
We 'just' need an equivalent to an EJB container for
swing application.
I think the concept of transaction can be borrow
in the same time, it could liberate us
from invokeLater and SwingWorker.

So in my opinion, adding bound properties
to the language is a bad idea.


I prefer to let that job to
Beans Binding
experts group (JSR 295) and its leader Scott Violet.

So is property syntax usefull ?

I think that even if bound properties are not managed
by the compiler, we need a property syntax
at least to insert a special attribute in the bytecode
that will be recognize by the reflection runtime
to provide property objects at runtime.

Property interceptor by the compiler

But if you think that this kind of AOP must
be done by the compiler, i propose
to allow to declare two a special methods
named set* and get* (the star is not a typo)
that can be used instead of a particular getter
or setter.

By example, a bean that declares two bound properties
background and foreground in that way
could be written like that :

  public class MyBean {
    public property Color background;
    public property Color foreground;

    public void set*(Property property,Object value) {
      Object oldValue=property.get(this);
      super();
      SwingPropertySupport.firePropertyChange(property,
        oldValue,property.get(this));
    }
  }

The compiler will generate foreground or background
setters by duplicate the set* code
for each setter.


java.lang.reflect.Property is the reflection
counterpart of a property at runtime
(I've just rename the Stephen Colebourne's property object to a more Java-like name),
super() in that context means set the property value
(pretty ugly isn't it) and
SwingPropertySupport is a new class that allow to
add/remove PropertyChangeListener for any
property of any bean.

To Link a property to a listener, we can use

  MyBean bean=...
  SwingPropertySupport.addPropertyChangeListener(
    bean,"background",new PropertyChangeListener() {
      ...
    });

Cheers,


Rémi

P.S : to the little Peter, you can't return a gift :)

Related Topics >>