summaryrefslogtreecommitdiff
path: root/src/test/java/luciano/AutoConstructorClass.oj
blob: 65f04ad008167c9ac864a2b4ac89f68ad094a34f (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
65
66
67
68
69
70
71
import luciano;

import io.devnulllabs.openjava.mop.*;
import io.devnulllabs.openjava.ptree.*;
import io.devnulllabs.openjava.syntax.*;
import io.devnulllabs.openjava.ptree.util.VariableBinder;

/**
 * This metaclass appends a constructor of a String parameter.
 * It makes no sense but shows an example of adding a special
 * statement of calling super constructor.
 */
public class AutoConstructorClass instantiates Metaclass extends OJClass {
    public convenient void translateDefinition() throws MOPException {
        System.out.println("translateDefinition() of " + getName());
        if (doesClassHaveStringCons())
            return;
        if (!doesSuperHaveDefaultCons())
            return;

        OJConstructor con =
            new OJConstructor(
                this,
                OJModifier.forModifier(OJModifier.PUBLIC),
                new OJClass[] { String.class },
                new OJClass[0],
                null,
                null /* temporally */
        );

        ExpressionList conargs = con.getParameterVariables();
        Expression conarg = conargs.get(0);

        /* "super()" */
        ConstructorInvocation ci =
            new ConstructorInvocation(new ExpressionList(), null);

        /* other part of constructors' body */
        StatementList body =
            makeStatementList(
                con.getEnvironment(),
                "/* test */" + "java.lang.System.out.println(" + conarg + ");");

        con.setTransference(ci);
        con.setBody(body);

        addConstructor(con);
    }

    private convenient boolean doesClassHaveStringCons() {
        try {
            this.getConstructor(new OJClass[] { String.class }, this);
            return true;
        } catch (NoSuchMemberException ex) {
            return false;
        }
    }

    private boolean doesSuperHaveDefaultCons() {
        OJClass baseclazz = this.getSuperclass();
        if (baseclazz == null)
            return false;
        try {
            baseclazz.getConstructor(new OJClass[0], this);
            return true;
        } catch (NoSuchMemberException ex) {
            return false;
        }
    }

}