summaryrefslogtreecommitdiff
path: root/tutorial/examples/autoimp/AutoImplementerClass.oj
blob: 29ca2b20952ee5b8ea5d9fc27c8c62bb48c2c2cc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
 * AutoImplementerClass.oj
 *
 * Apr 29, 1999, by Michiaki Tatsubori
 * Feb 2, 1999, by Michiaki Tatsubori
 */
package examples.autoimp;


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


/**
 * The metaclass <code>AutoImprementerClass</code> provides classes
 * with a facility automatically implementing null methods for
 * not implemented methods.
 * <p>
 *
 * @author   Michiaki Tatsubori
 * @version  1.0
 * @see openjava.mop.OJClass#translateDefinition()
 * @see openjava.mop.OJClass#isRegisteredModifier()
 */
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()
                || hasDeclaredMethod( methods[i] ))  continue;
            addMethod( makeNullMethod( methods[i] ) );
        }
    }

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

    private OJMethod makeNullMethod( OJMethod m ) throws MOPException {
        /* generates a new method without body */
        OJMethod result = new OJMethod( this,
            m.getModifiers().remove( OJModifier.ABSTRACT ),
            m.getReturnType(), m.getName(), m.getParameterTypes(),
            m.getExceptionTypes(), null
            );
        /* generates a return statement */
        StatementList body = new StatementList();
        if (m.getReturnType() == OJSystem.VOID) {
            body.add( new ReturnStatement() );
        } else {
            body.add( new ReturnStatement( Literal.constantNull() ) );
        }
        result.setBody( body );
        return result;
    }

}