1 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.FieldNode; 52 import org.codehaus.groovy.ast.MethodNode; 53 import org.codehaus.groovy.ast.Parameter; 54 import org.codehaus.groovy.ast.PropertyNode; 55 import org.codehaus.groovy.ast.expr.BinaryExpression; 56 import org.codehaus.groovy.ast.expr.BooleanExpression; 57 import org.codehaus.groovy.ast.expr.ConstantExpression; 58 import org.codehaus.groovy.ast.expr.FieldExpression; 59 import org.codehaus.groovy.ast.stmt.ExpressionStatement; 60 import org.codehaus.groovy.ast.stmt.IfStatement; 61 import org.codehaus.groovy.ast.stmt.Statement; 62 import org.codehaus.groovy.runtime.InvokerHelper; 63 import org.codehaus.groovy.syntax.Token; 64 65 70 public class IfElseTest extends TestSupport { 71 72 public void testLoop() throws Exception { 73 ClassNode classNode = new ClassNode("Foo", ACC_PUBLIC, "java.lang.Object"); 74 classNode.addConstructor(new ConstructorNode(ACC_PUBLIC, null)); 75 classNode.addProperty(new PropertyNode("bar", ACC_PUBLIC, "java.lang.String", "Foo", null, null, null)); 76 77 classNode.addProperty(new PropertyNode("result", ACC_PUBLIC, "java.lang.String", "Foo", null, null, null)); 78 79 BooleanExpression expression = 80 new BooleanExpression( 81 new BinaryExpression( 82 new FieldExpression( 83 new FieldNode("bar", ACC_PRIVATE, "java.lang.String", "Foo", ConstantExpression.NULL)), 84 Token.newSymbol("==", 0, 0), 85 new ConstantExpression("abc"))); 86 87 Statement trueStatement = 88 new ExpressionStatement( 89 new BinaryExpression( 90 new FieldExpression( 91 new FieldNode("result", ACC_PRIVATE, "java.lang.String", "Foo", ConstantExpression.NULL)), 92 Token.newSymbol("=", 0, 0), 93 new ConstantExpression("worked"))); 94 95 Statement falseStatement = createPrintlnStatement(new ConstantExpression("false")); 96 97 IfStatement statement = new IfStatement(expression, trueStatement, falseStatement); 98 classNode.addMethod(new MethodNode("ifDemo", ACC_PUBLIC, "void", Parameter.EMPTY_ARRAY, statement)); 99 100 Class fooClass = loadClass(classNode); 101 assertTrue("Loaded a new class", fooClass != null); 102 103 Object bean = fooClass.newInstance(); 104 assertTrue("Managed to create bean", bean != null); 105 106 assertSetProperty(bean, "bar", "abc"); 107 108 System.out.println("################ Now about to invoke method"); 109 110 Object [] array = { 111 }; 112 113 InvokerHelper.invokeMethod(bean, "ifDemo", array); 114 115 System.out.println("################ Done"); 116 117 assertGetProperty(bean, "result", "worked"); 118 } 119 } 120 | Popular Tags |