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