Visitor :

May 4, 2009

BCEL in java6








Java 6 have bcel packages, so I made interesting code to print "Hello World" every first-experience java developers have to meet.


There are no library have to include. That's my favorite!! 






BCEL tutorial is below web site.


























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");


}


}














After running this class, I can find "build/HelloWorld.class". 


By using jad, I can see the decompiled class.




// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.


// Jad home page: http://www.kpdus.com/jad.html


// Decompiler options: packimports(3) 


// Source File Name:   






import java.io.PrintStream;






public class HelloWorld


{






    public HelloWorld()


    {


    }






    public static void main(String args[])


    {


        System.out.println("Hello World!!");


    }


}








No comments:

Post a Comment