import
org.objectweb.asm.ClassWriter;
import
org.objectweb.asm.Label;
import
org.objectweb.asm.MethodVisitor;
import
org.objectweb.asm.Opcodes;
public
class
HelloWorldASM implements
Opcodes
{
public
interface
Greeting{void sayHello();}
static
byte[]
generateBytecode() throws
Exception
{
ClassWriter cw = new
ClassWriter(0);
MethodVisitor mv;
cw.visit(V1_6, ACC_PUBLIC + ACC_SUPER, "HelloWorld",
null,
"java/lang/Object",
new
String[]{"HelloWorldASM$Greeting"});
{
mv = cw.visitMethod(ACC_PUBLIC,
"<init>",
"()V",
null,
null);
mv.visitCode();
Label l0 =
new
Label();
mv.visitLabel(l0);
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object",
"<init>",
"()V");
mv.visitInsn(RETURN);
Label
l1 = new
Label();
mv.visitLabel(l1);
mv.visitLocalVariable("this",
"LHelloWorld;",
null,
l0, l1, 0);
mv.visitMaxs(1,
1);
mv.visitEnd();
}
{
mv = cw.visitMethod(ACC_PUBLIC,
"sayHello",
"()V",
null,
null);
mv.visitCode();
Label l0 =
new Label();
mv.visitLabel(l0);
mv.visitFieldInsn(GETSTATIC, "java/lang/System",
"out",
"Ljava/io/PrintStream;");
mv.visitLdcInsn("Hello
World!");
mv.visitMethodInsn(INVOKEVIRTUAL,
"java/io/PrintStream",
"println",
"(Ljava/lang/String;)V");
mv.visitInsn(RETURN);
Label
l2 = new Label();
mv.visitLabel(l2);
mv.visitLocalVariable("this",
"LHelloWorld;",
null,
l0, l2, 0);
mv.visitMaxs(2,
1);
mv.visitEnd();
}
cw.visitEnd();
return
cw.toByteArray();
}
public
static
void
main(String[] args) throws
Exception
{
final
byte[]
bytecode = generateBytecode();
final
Class clazz = Class.forName(
"HelloWorld",
false,
new
ClassLoader()
{
protected
Class findClass(String name)
{
return
defineClass(name,
bytecode, 0,
bytecode.length);
}
});
final
Greeting h = (Greeting)clazz.newInstance();
h.sayHello();
}
}