import com.sun.org.apache.bcel.internal.Constants;
import com.sun.org.apache.bcel.internal.generic.ArrayType;
import com.sun.org.apache.bcel.internal.generic.ClassGen;
import com.sun.org.apache.bcel.internal.generic.ConstantPoolGen;
import com.sun.org.apache.bcel.internal.generic.InstructionFactory;
import com.sun.org.apache.bcel.internal.generic.InstructionList;
import com.sun.org.apache.bcel.internal.generic.MethodGen;
import com.sun.org.apache.bcel.internal.generic.ObjectType;
import com.sun.org.apache.bcel.internal.generic.PUSH;
import com.sun.org.apache.bcel.internal.generic.Type;
public class SimpleHelloWorldBuilder {
public static void main(String[] args) throws Exception {
// public HellowWorld extends java.lang.Object
ClassGen classGen = new ClassGen("HelloWorld", "java.lang.Object", "", Constants.ACC_PUBLIC
| Constants.ACC_SUPER, null);
ConstantPoolGen constantPoolGen = classGen.getConstantPool();
InstructionList instructionList = new InstructionList();
// public static void main
MethodGen methodGen = new MethodGen(Constants.ACC_PUBLIC | Constants.ACC_STATIC, Type.VOID,
// (String[] args)
new Type[] {new ArrayType(Type.STRING, 1)}, new String[] {"args"}, "main", "HelloWorld", instructionList, constantPoolGen);
InstructionFactory instructionFactory = new InstructionFactory(classGen);
classGen.addEmptyConstructor(Constants.ACC_PUBLIC);
// System.out.println
ObjectType printStream = new ObjectType("java.io.PrintStream");
instructionList.append(instructionFactory.createFieldAccess("java.lang.System", "out", printStream, Constants.GETSTATIC));
// "Hello world!!"
instructionList.append(new PUSH(constantPoolGen, "Hello World!!"));
instructionList.append(instructionFactory.createInvoke("java.io.PrintStream", "println", Type.VOID,
new Type[] {Type.STRING}, Constants.INVOKEVIRTUAL));
classGen.addMethod(methodGen.getMethod());
instructionList.dispose();
classGen.getJavaClass().dump("build/HelloWorld.class");
}
}