public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!!");
}
}
生成用コード。
import org.apache.bcel.Constants;
import org.apache.bcel.generic.ArrayType;
import org.apache.bcel.generic.ClassGen;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.InstructionConstants;
import org.apache.bcel.generic.InstructionFactory;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.MethodGen;
import org.apache.bcel.generic.ObjectType;
import org.apache.bcel.generic.PUSH;
import org.apache.bcel.generic.Type;
public class Main {
public static void main(String[] args) throws Exception {
ClassGen helloWorldClassGen =
new ClassGen(
"HelloWorld",
"java.lang.Object",
"<generated>",
Constants.ACC_PUBLIC | Constants.ACC_SUPER,
null
);
ConstantPoolGen helloWorldClassConstantPoolGen =
helloWorldClassGen.getConstantPool();
InstructionList instructionList = new InstructionList();
MethodGen mainMethodGen =
new MethodGen(
Constants.ACC_STATIC | Constants.ACC_PUBLIC,
Type.VOID,
new Type[] { new ArrayType(Type.STRING, 1) },
new String[] { "args" },
"main",
"HelloWorld",
instructionList,
helloWorldClassConstantPoolGen
);
InstructionFactory instructionFactory =
new InstructionFactory(helloWorldClassGen);
ObjectType printStreamObjectType = new ObjectType("java.io.PrintStream");
instructionList.append(
instructionFactory.createFieldAccess(
"java.lang.System",
"out",
printStreamObjectType,
Constants.GETSTATIC
)
);
instructionList.append(new PUSH(helloWorldClassConstantPoolGen, "Hello, World!!"));
instructionList.append(
instructionFactory.createInvoke(
"java.io.PrintStream",
"println",
Type.VOID,
new Type[] { Type.STRING },
Constants.INVOKEVIRTUAL
)
);
instructionList.append(InstructionConstants.RETURN);
mainMethodGen.setMaxStack();
helloWorldClassGen.addMethod(mainMethodGen.getMethod());
instructionList.dispose();
helloWorldClassGen.addEmptyConstructor(Constants.ACC_PUBLIC);
helloWorldClassGen.getJavaClass().dump("HelloWorld.class");
}
}
0 件のコメント:
コメントを投稿