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 org.codehaus.groovy.ast.ClassNode;
50 import org.codehaus.groovy.ast.ConstructorNode;
51 import org.codehaus.groovy.ast.MethodNode;
52 import org.codehaus.groovy.ast.Parameter;
53 import org.codehaus.groovy.ast.PropertyNode;
54 import org.codehaus.groovy.ast.Type;
55 import org.codehaus.groovy.ast.expr.VariableExpression;
56 import org.codehaus.groovy.ast.stmt.ForStatement;
57 import org.codehaus.groovy.ast.stmt.Statement;
58 import org.codehaus.groovy.runtime.InvokerHelper;
59 import org.codehaus.groovy.runtime.InvokerInvocationException;
60
61 /***
62 *
63 * @author <a href="mailto:james@coredevelopers.net">James Strachan</a>
64 * @version $Revision: 1.5 $
65 */
66 public class ForTest extends TestSupport {
67
68 public void testLoop() throws Exception {
69 ClassNode classNode = new ClassNode("Foo", ACC_PUBLIC, "java.lang.Object");
70 classNode.addConstructor(new ConstructorNode(ACC_PUBLIC, null));
71 classNode.addProperty(new PropertyNode("bar", ACC_PUBLIC, "java.lang.String", "Foo", null, null, null));
72
73 Parameter[] parameters = { new Parameter("coll")};
74
75 Statement loopStatement = createPrintlnStatement(new VariableExpression("i"));
76
77 ForStatement statement = new ForStatement("i", Type.DYNAMIC_TYPE, new VariableExpression("coll"), loopStatement);
78 classNode.addMethod(new MethodNode("iterateDemo", ACC_PUBLIC, "void", parameters, statement));
79
80 Class fooClass = loadClass(classNode);
81 assertTrue("Loaded a new class", fooClass != null);
82
83 Object bean = fooClass.newInstance();
84 assertTrue("Managed to create bean", bean != null);
85
86 System.out.println("################ Now about to invoke method");
87
88 Object[] array = { new Integer(1234), "abc", "def" };
89
90 try {
91 InvokerHelper.invokeMethod(bean, "iterateDemo", new Object[] {array});
92 }
93 catch (InvokerInvocationException e) {
94 System.out.println("Caught: " + e.getCause());
95 e.getCause().printStackTrace();
96 fail("Should not have thrown an exception");
97 }
98 System.out.println("################ Done");
99 }
100 }