KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > python > compiler > AdapterMaker


1 // Copyright (c) Corporation for National Research Initiatives
2

3 package org.python.compiler;
4
5 import java.util.Hashtable JavaDoc;
6 import java.util.Enumeration JavaDoc;
7 import java.lang.reflect.Method JavaDoc;
8 import java.io.*;
9
10
11 public class AdapterMaker extends ProxyMaker
12 {
13     public AdapterMaker(Class JavaDoc interfac) {
14         super(interfac.getName()+"$Adapter", interfac);
15     }
16
17     public void build() throws Exception JavaDoc {
18         names = new Hashtable JavaDoc();
19
20         //Class superclass = org.python.core.PyAdapter.class;
21
int access = ClassFile.PUBLIC | ClassFile.SYNCHRONIZED;
22         classfile = new ClassFile(myClass, "java/lang/Object", access);
23
24         classfile.addInterface(mapClass(interfaces[0]));
25
26         addMethods(interfaces[0], new Hashtable JavaDoc());
27         addConstructors(Object JavaDoc.class);
28         doConstants();
29     }
30
31
32     public static String JavaDoc makeAdapter(Class JavaDoc interfac, OutputStream ostream)
33         throws Exception JavaDoc
34     {
35         AdapterMaker pm = new AdapterMaker(interfac);
36         pm.build();
37         pm.classfile.write(ostream);
38         return pm.myClass;
39     }
40
41     public void doConstants() throws Exception JavaDoc {
42         for (Enumeration JavaDoc e=names.keys(); e.hasMoreElements();) {
43             String JavaDoc name = (String JavaDoc)e.nextElement();
44             classfile.addField(name, "Lorg/python/core/PyObject;",
45                                ClassFile.PUBLIC);
46         }
47     }
48
49     public void addMethod(Method JavaDoc method, int access) throws Exception JavaDoc {
50         Class JavaDoc[] parameters = method.getParameterTypes();
51         Class JavaDoc ret = method.getReturnType();
52         String JavaDoc sig = makeSignature(parameters, ret);
53
54         String JavaDoc name = method.getName();
55         //System.out.println(name+": "+sig);
56
names.put(name, name);
57
58         Code code = classfile.addMethod(name, sig, ClassFile.PUBLIC);
59
60         code.aload(0);
61         int pyfunc = code.pool.Fieldref(classfile.name, name,
62                                         "Lorg/python/core/PyObject;");
63         code.getfield(pyfunc);
64         code.dup();
65         Label returnNull = code.getLabel();
66         code.ifnull(returnNull);
67         callMethod(code, name, parameters, ret, method.getExceptionTypes());
68         returnNull.setPosition();
69         doNullReturn(code, ret);
70     }
71 }
72
Popular Tags