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 package org.codehaus.groovy.classgen;
48
49 import java.io.*;
50 import java.util.ArrayList;
51 import java.util.List;
52
53 import org.codehaus.groovy.runtime.InvokerHelper;
54 import org.objectweb.asm.ClassWriter;
55 import org.objectweb.asm.util.CheckClassAdapter;
56 import org.objectweb.asm.util.ASMifierClassVisitor;
57
58 import groovy.lang.MetaClassRegistry;
59 import groovy.lang.MetaMethod;
60 import groovy.util.GroovyTestCase;
61
62 /***
63 *
64 * @author <a href="mailto:james@coredevelopers.net">James Strachan</a>
65 * @version $Revision: 1.5 $
66 */
67 public class ReflectorGeneratorTest extends GroovyTestCase {
68
69 public void testGenerator() throws Exception {
70 List methods = new ArrayList();
71 methods.add(new MetaMethod("toCharArray", String.class, new Class[0], char[].class, 0));
72
73 testMethods(methods);
74 }
75
76 public void testObjectGenerator() throws Exception {
77 List methods = InvokerHelper.getMetaClass(new Object()).getMethods();
78 testMethods(methods);
79 }
80
81 public void testDummyReflector() throws Exception {
82 DummyReflector dummy = new DummyReflector();
83 assertTrue(dummy != null);
84 }
85
86 protected void testMethods(List methods) throws Exception {
87 ReflectorGenerator generator = new ReflectorGenerator(methods);
88 String name = getClass().getName() + "." + getMethodName();
89 ClassWriter cw = new ClassWriter(true);
90
91
92 ASMifierClassVisitor dumper = new ASMifierClassVisitor(new PrintWriter(new OutputStreamWriter(System.out)));
93
94
95 generator.generate(new CheckClassAdapter(cw), name);
96
97 byte[] bytecode = cw.toByteArray();
98
99
100 String fileName = "target/" + name + ".class";
101 FileOutputStream out = new FileOutputStream(fileName);
102 out.write(bytecode);
103 out.close();
104
105
106 ASMifierClassVisitor.main(new String[] { fileName });
107
108
109 MetaClassRegistry registry = new MetaClassRegistry();
110 Class type = registry.createReflectorClass(getClass().getClassLoader(),name, bytecode);
111
112 Object reflector = type.newInstance();
113
114 System.out.println("Created new reflector: " + reflector);
115 }
116 }