Multimethods for Java

By: on June 23, 2006

Dynamic dispatch is a mechanism for selecting a method based on the runtime types of the parameters supplied. Java dispatches instance methods dynamically, using the runtime type of the receiver to choose the code to invoke and ignoring the types of the other parameters (just like Python and many other object-oriented languages). This is called single dispatch. Unfortunately, Java’s dispatching is limited in two important ways: it doesn’t allow class extensions, and it doesn’t support multiple dispatch, as implemented in many other object-oriented languages.

I have written some code which uses reflection and proxy generation to conveniently implement dynamic multiple dispatch for Java. It uses C3 linearization to determine the method to invoke. This algorithm was originally devised for Dylan. You can see the source here.

This implementation supports subtyping of both arrays and primitive Java types such as int, byte, char, but does not yet support Java 1.5’s generics. The subtyping relation for arrays and primitive types is based on Java’s notion of assignability – see the documentation for details.

Here’s a trivial example of using the dynamic dispatch library:

  import net.lshift.java.dispatch.DynamicDispatch;

  // define an interface
  public interface NumberPredicate {
      public boolean evaluate(Number n);
  }

  // implement it for some argument types
  public class Exact {
      public boolean evaluate(Float f)  { return false; }
      public boolean evaluate(Double f) { return false; }
      public boolean evaluate(Number n) { return true; }
  }

  // create a dynamic dispatcher
  NumberPredicate exact = (NumberPredicate)
    DynamicDispatch.proxy(NumberPredicate.class, new Exact());

Now, code making use of exact can call the evaluate method with a Number instance, and the DynamicDispatch proxy that is backing the NumberPredicate interface will find the most appropriate method on Exact to invoke based on the runtime type of the argument to evaluate. So, for instance:

  exact.evaluate(new Float(12.3)); // returns false.
  exact.evaluate(new Integer(34)); // returns true.

There are several reasons having dynamic dispatch (and multiple dispatch) is useful when programming for Java:

If you want to extend an existing set of classes (for instance, to add an aspect – see below), normally you’d create an interface encapsulating your new feature, and make all the classes in the set implement it. If you are not able to modify the classes, one approach is to create wrapper classes for each, and somehow choose a wrapper class at runtime based on the type of the object you’re working with. You might implement this by myObject.getWrapperClass() – but wait! This makes getWrapperClass a new method that needs to be added: precisely the problem you set out originally to solve. Dynamic (single) dispatch helps you out here by conveniently automating the required wrapping and method selection.

You might also want to use multiple dispatch, dispatching on the types of multiple arguments. Neither the Java language nor the Java virtual machine supports multiple dispatch. In some cases overloading suffices, but in many it does not.

Dynamic multiple dispatch takes Java’s static multiple dispatch (overloading) and implements it dynamically to create multimethods. You write overloaded methods – but using DynamicDispatch, you then create a proxy which implements the methods in an interface as multimethods, dispatching to one of your overloaded methods according to the run time types of the arguments.

Dynamic dispatch is useful for adding aspects. For example, you might use dynamic dispatch to write a Java object pretty printer, or custom serializer. I’ve employed it for writing a general equality function which is independent of the object’s own implementation of equals, which I find useful in unit tests. I’ll write about that in a later post.

If this kind of thing interests you, MultiJava, a compiler for a multiply-dispatched variant of Java, might be worth a look.

FacebookTwitterGoogle+

11 Comments

  1. arun says:

    i aml confusing in dynamic dispatch, double dynamic dispatch , multiple dynamic dispatch.Can you explain me in a simple way.(the basic of it with examples.)

  2. david says:

    http://en.wikipedia.org/wiki/Multiple_dispatch

    This covers it as well as I am going to be able to

  3. jan says:

    I’m working on an event dispatching mechanism for a event based integration framework written in Java. I would like to do dynamic dispatching in order to allow for developers to define event listeners that accept only selected event types based on the (overloaded) method signatures they provide. Your code looks very promising, but I’m wondering, whether it can be used with my own class hierarchy as it seems to support only primitive types. Do you think it could easily be extended to handle arbitrary types?

    thanks a lot,
    Jan

  4. david says:

    There is special handling for java primitive types, but all types are supported.

  5. david says:

    Have a look at DynamicDispatchTest.java, which creates various classes, and then does dynamic dispatch using them.

    Here is a new version of
    lshift-java
    BTW. I don’t think there are any significant changes to the dynamic dispatch code, however.

  6. jan says:

    Hi David,

    thanks a lot for your replies and the link to the new version. I’ll definitely try to integrate your dispatching. Just in case you are interested, I’m working within a research project developing an open source EBI framework for the integration of robotic systems. I’ll post a link here as soon as there is anything presentable available.
    Thanks again.

    Jan

  7. Jan Schaefer says:

    Hi again,

    when tinkering with DynamicDispatch I found that inherited methods are not invokable on the generated proxy:

    package net.lshift.java;</p>

    <p>import net.lshift.java.dispatch.DynamicDispatch;</p>

    <p>public class DynamicDispatchTest
    {</p>

    ::CODECOLORER_COMMENT_4::

    <p>}

    This is a feature we definitely need, so I started to dive into your code a bit deeper. What I came up with so far is, that by changing lines 348 and 349 in file net.lshift.java.dispatch.DynamicDispatch.java to call Class.getMethods() instead of Class.getDeclaredMethods() inherited methods become callable and the test will run fine:

    // net.lshift.java.dispatch.DynamicDispatch.java</p>

    <p>public class DynamicDispatch
    {</p>

    ::CODECOLORER_COMMENT_5::

    <p>//          Method [] procedures = constraint.getDeclaredMethods();
    //          Method [] methods = implementation.getDeclaredMethods();
                Method [] procedures = constraint.getMethods();
                Method [] methods = implementation.getMethods();
                for(int p = 0; p != procedures.length; ++p) {
                    this.procedures.put
                        (procedures[p], new Procedure(procedures[p], methods));
                }
            }</p>

    ::CODECOLORER_COMMENT_6::

    <p>}

    Now I’m wondering whether this might have undesirable side effects. Do you see any problems with the changes I made?

    Thanks once more,
    Jan

  8. Jan Schaefer says:

    Oups, for some reason the code blocks were scrambled so I submitted the code samples to pastebin,com.

    The test:
    http://pastebin.com/f49ab08de

    My changes:
    http://pastebin.com/f7d93e5eb

  9. KP says:

    @david: This is awesome! The hyperlink you have here, though, https://www.lshift.net/downloads/lshift-java-2.1.11.tar.gz, is dead. :( Care to repost it?

  10. david says:

    I’ve published the source in bitbucket: see the (updated) link in the article.

  11. david says:

    getMethods() can return multiple methods with identical signatures. That then leaves me to compute the linearization to work out which one is relevant to call. I feel that’s just too complicated. Instead, you can compose methods from multiple classes by listing multiple objects to dispatch to. The order is then the explicit order you used when constructing the proxy. This is more flexible than using sub-classing in any case.

Post a comment

Your email address will not be published.

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>