Qi4j

Tutorial 8 - Generic mixins

In this tutorial we will look at how to use generic Fragments. So far all Fragments, i.e. the Concern and Mixins, have directly implemented the domain interface. But sometimes it is useful to be able to provide a generic implementation of an interface. An example of this is the HelloWorldState interface. Since it only handles properties, and uses the JavaBean rules for naming getters and setters we could create a mixin that handles invocations of such methods automatically for us by storing the properties in a map and use the methods to look them up.

Implementing a generic Fragment is done by creating a class that implements the interface java.lang.proxy.InvocationHandler. This has a single "invoke" method which is passed the object that was invoked (the Composite in this case), the method, and the arguments. The Fragment is then allowed to implement the method any way it wants.

Since interfaces with only Properties is such a common case Qi4j already has a generic Mixin that implements the Properties management described above. The class is aptly named PropertyMixin.

While we could use it, for now we will implement it ourselves to get a feel for how generic Mixins work.

Steps for this tutorial:

  1. Remove the HelloWorldStateMixin
  2. Add a GenericPropertyMixin, and have it implement InvocationHandler
  3. Inject "@PropertyField State state" in the mixin. The State interface will give you access to the Properties for the Composite which Qi4j manages for you
  4. On call to invoke(), delegate to the State interface to get the Property for the invoked method
  5. Add the mixin to the Composite

Solution

If you have successfully completed the task, you should end up with the following artifacts;

GenericPropertyMixin.javaexternal link
HelloWorldBehaviour.javaexternal link
HelloWorldBehaviourMixin.javaexternal link
HelloWorldComposite.javaexternal link
HelloWorldState.javaexternal link

Powered by SiteVisionexternal link.