Dynamic Mixins is a possible application of our enhanced VM. We developed a prototype API for working with dynamic mixins in Java.

The following example shows how mixins can be used in our approach to extend the functionality of an existing class. Assume, that we have a class Point2D, which implements two-dimensional points.

public class Point2D {
  private int x;
  private int y;

  public int getX() { return x; }
  public void setX(int x) { this.x = x; }
  public int getY() { return y; }
  public void setY(int y) { this.y = y; }

We would like to extend this class so that it can handle three-dimensional points. First we specify the 3D behaviour by an interface Point3D.

interface Point3D {
  public int getZ();
  public void setZ(int z);

Then we implement the 3D behaviour by a mixin class Mixin3D which implements the interface Point3D.

public class Mixin3D implements Point3D {
  private int z;

  public int getZ() { return z; }
  public void setZ(int z) { this.z = z; }

In order to add the 3D behaviour to the class Point2D we call:

Mixin.addMixin(Point2D.class, Mixin3D.class);

This will add all features of the class Mixin3D to the class Point2D. In other words, the class Point2D is dynamically redefined so that it contains a field z as well as the methods getZ() and setZ() with their bytecodes. Since Mixin3D implements the interface Point3D, the class resulting from adding Mixin3D to Point2D will implement Point3D as well. We can now create an instance of Point2D and use it as a Point3D object, for example:

Point2D point2d = new Point2D(); 
Point3D point3d = (Point3D) point2d;
System.out.println("Point at " + point2d.getX() + "/" + point2d.getY() + "/" + point3d.getZ());

Note, that our approach does not require new Java syntax. A mixin is an ordinary Java class with fields and methods and possibly implementing some interfaces. Also the target class does not need special syntax for allowing it to be extended by mixin classes. Any number of mixin classes can be added to a target class using a sequence of addMixin() calls. This happens at run time and allows the dynamic extension of classes with extra essay functionality.

This example code can be downloaded as a netbeans or eclipse project archive. At the current stage of development, this example code can only be run when specifying the following command line arguments to the java runtime (where PATH_TO_JRE is typically the jre subdirectory of the Java SDK installation directory or the Java JRE installation directory itself):

$ java -javaagent:/PATH_TO_JRE/lib/ext/dcevm.jar

Poster (Publication at PPPJ’10):
Mixin Poster (PPPJ'10)

Post a Comment

Your email is never published nor shared. Required fields are marked *


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=""> <s> <strike> <strong>