summaryrefslogtreecommitdiff
path: root/tutorial/examples/rtrefl/RTMetaObject.java
blob: 13486ae95b2e1ab4f01bb2073190d5f6f4bbd8bf (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
72
73
74
75
76
77
78
79
80
81
package examples.rtrefl;


import java.lang.reflect.*;


/**
 * The class RTMetaObject
 * Exception handling is not implemented.
 */
public class RTMetaObject
{
    private RTMetaLevel baseObj;

    public RTMetaObject(RTMetaLevel base_obj) {
    this.baseObj = base_obj;
    }

    public Object trapMethodCall(String name, Class[] paramTypes, Object[] args)
    {
    try {
        Method method = baseObj.getClass().getMethod(name, paramTypes);
        return method.invoke(baseObj, args);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    }

    public Object trapFieldRead(String name) {
    try {
        Field field = baseObj.getClass().getField(name);
        return field.get(baseObj);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    }

    public void trapFieldWrite(String name, Object rvalue) {
    try {
        Field field = baseObj.getClass().getField(name);
        field.set(baseObj, rvalue);
    } catch (Exception e) {
        e.printStackTrace();
    }
    }
}


/*****
class Foo {
    int f(int a) {}
    int l;
}
...
Foo foo;  foo.l = expr;  a = foo.l;

->

class Foo implements Metalevel {
    public examples.rtrefl.RTMetaObject mt;
    int org_f(int a) {}
    int f(int a) {
        Object[] args = new Object[]{ new Integer(a) };
        Class[] argTypes = new Class[]{ int.class };
    Object result = mt.trapMethodCall("org_f", argTypes, args);
        return ((Integer) result).intValue();
    }
    int read_l() {
        Object result = mt.trapFieldRead("l");
        return ((Integer) result).intValue();
    }
    int write_l(int rvalue) {
        mt.trapFieldWrite("l", new Integer(rvalue));
        return rvalue;
    }
}
...
Foo foo;  foo.write_l(expr);  a = foo.read_l();
*****/