OpenJava Tutorial


5. Automatic Methods Implementation

In this section, an example of simple translation at callee-side is described.

The callee-side of a class is whole the declration source code of the class. Metaprogram in the metaclass for that class (base class) introspects that class definition in this class object through the inheriting OJClass interface.

Imagine an utility metaclass which automatically implements empty methods in its base classes according to their interfaces.

5.1. What the base-level program should look like

A base class QuickTest has to implement an interface java.awt.event.WindowListener, which has several methods to have to be implemented, but we want to make most of these methods to have empty body, i.e. do nothing.


import java.awt.event.*;
public class QuickTest instantiates AutoImplementerClass
    implements WindowListener
{
    public void windowClosed( WindowEvent e ) { System.exit( 0 ); }
}

5.2. What the base-level program should be translated

Like following:


public class QuickTest instantiates AutoImplementerClass
    implements WindowListener
{
    public void windowClosed( WindowEvent e ) { System.exit( 0 ); }
    public void windowIconified( WindowEvent e ) { return; }
    public void windowDeactivated( WindowEvent e ) { return; }
    ....
}

5.3. Write a meta-level program

So.


import openjava.mop.*;
import openjava.ptree.*;
import openjava.syntax.*;

public class AutoImplementerClass instantiates Metaclass extends OJClass
{
    public void translateDefinition() throws MOPException {
        OJMethod[] methods = getInheritedMethods();
        for (int i = 0; i < methods.length; ++i) {
            if (! methods[i].getModifiers().isAbstract()
                || methods[i].getReturnType() != OJSystem.VOID
                || hasDeclaredMethod( methods[i] ))  continue;
            addMethod( makeEmptyMethod( methods[i] ) );
        }
    }
    ....
}


    private boolean hasDeclaredMethod( OJMethod m ) {
	try {
	    getDeclaredMethod( m.getName(), m.getParameterTypes() );
	    return true;
	} catch ( NoSuchMemberException e ) {
	    return false;
	}
    }


    private OJMethod makeEmptyMethod( OJMethod m ) throws MOPException {
        /* generates a new method without body */
        return new OJMethod( this,
            m.getModifiers().remove( OJModifier.ABSTRACT ),
            m.getReturnType(), m.getName(), m.getParameterTypes(),
            m.getExceptionTypes(),
            new StatementList( new ReturnStatement() )
            );
    }

Please send any message to :
mich@acm.org

Copyright (C) 1999 by Michaki Tatsubori.
Java(TM) is a trademark of Sun Microsystems, Inc.