1 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 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 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 95 generator.generate(new CheckClassAdapter(cw), name); 96 97 byte[] bytecode = cw.toByteArray(); 98 99 String fileName = "target/" + name + ".class"; 101 FileOutputStream out = new FileOutputStream(fileName); 102 out.write(bytecode); 103 out.close(); 104 105 ASMifierClassVisitor.main(new String [] { fileName }); 107 108 MetaClassRegistry registry = new MetaClassRegistry(); 110 Class type = registry.loadClass(name, bytecode); 111 112 Object reflector = type.newInstance(); 113 114 System.out.println("Created new reflector: " + reflector); 115 } 116 } 117 | Popular Tags |