1 26 27 package net.sourceforge.groboutils.codecoverage.v2; 28 29 import java.io.ByteArrayOutputStream ; 30 import java.io.IOException ; 31 32 import org.apache.bcel.Constants; 33 import org.apache.bcel.classfile.JavaClass; 34 import org.apache.bcel.generic.ArrayType; 35 import org.apache.bcel.generic.ClassGen; 36 import org.apache.bcel.generic.ConstantPoolGen; 37 import org.apache.bcel.generic.InstructionFactory; 38 import org.apache.bcel.generic.InstructionList; 39 import org.apache.bcel.generic.MethodGen; 40 import org.apache.bcel.generic.Type; 41 42 43 44 51 public class CreateMainClassHelper 52 { 53 private static final Class THIS_CLASS = CreateMainClassHelper.class; 54 55 private String className; 56 private ClassGen cg; 57 private MethodGen mg; 58 59 private JavaClass jc; 60 private byte[] bytecode; 61 62 public ConstantPoolGen cp; 63 public InstructionList il; 64 public InstructionFactory factory; 65 66 67 68 public CreateMainClassHelper( String className ) 69 { 70 this.className = className; 71 72 this.cg = new ClassGen( className, 73 Object .class.getName(), "<generated>", 74 Constants.ACC_PUBLIC | Constants.ACC_SUPER, null ); 75 this.cp = this.cg.getConstantPool(); 76 this.il = new InstructionList(); 77 this.mg = new MethodGen( 78 Constants.ACC_STATIC | Constants.ACC_PUBLIC, Type.VOID, new Type[] { new ArrayType(Type.STRING, 1) }, 82 new String [] { "argv" }, "main", "HelloWorld", this.il, this.cp ); 85 this.factory = new InstructionFactory( this.cg ); 86 } 87 88 89 public void close() 90 throws IOException 91 { 92 this.mg.setMaxStack(); 93 this.cg.addMethod( this.mg.getMethod() ); 94 this.il.dispose(); 95 this.cg.addEmptyConstructor( Constants.ACC_PUBLIC ); 96 97 this.il = null; 98 this.mg = null; 99 this.cp = null; 100 101 this.jc = cg.getJavaClass(); 102 103 104 ByteArrayOutputStream baos = new ByteArrayOutputStream (); 105 this.jc.dump( baos ); 106 this.bytecode = baos.toByteArray(); 107 } 108 109 110 public JavaClass getJavaClass() 111 { 112 return this.jc; 113 } 114 115 116 public byte[] getBytecode() 117 { 118 return this.bytecode; 119 } 120 121 122 public Class getGenClass() 123 throws ClassNotFoundException 124 { 125 Class cc = BytecodeLoaderUtil.loadClassFromBytecode( 126 this.className, this.bytecode ); 127 return cc; 128 } 129 130 } 131 132 | Popular Tags |