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.
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 ); } }
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; } .... }
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() ) ); }