asm 之Hello World

 

import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.Method;

import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;


public class HelloAsm {

	public static void main(String[] args)throws Exception{
		
		System.out.println("enter main");
		
		ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
		// 类访问开始
		cw.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC, "com/cjf/Hello", null, "java/lang/Object", null);
		
		// 至少提供一个构造函数
		MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
		// 代码开始:必须
		mv.visitCode();
		mv.visitVarInsn(Opcodes.ALOAD, 0);
		// 调用Object 构造函数
		mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V");
		mv.visitInsn(Opcodes.RETURN);
		// 计算栈和局部变量最大空间:必须
		mv.visitMaxs(0, 0);
		mv.visitEnd();
		
		
		// 生成main 方法
		mv = cw.visitMethod(Opcodes.ACC_PUBLIC|Opcodes.ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null);
		mv.visitCode();
		mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
		mv.visitLdcInsn("Hello World!");
		// 调用实例重载方法
		mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V");
		mv.visitInsn(Opcodes.RETURN);
		mv.visitMaxs(0, 0);
		mv.visitEnd();
		
		// 类结束:必须
		cw.visitEnd();
		
		final byte[] bytes = cw.toByteArray();
		Class<?> clazz = new ClassLoader() {
			protected Class<?> findClass(String name) throws ClassNotFoundException{
				return defineClass(name, bytes,0, bytes.length);
			}
		}.loadClass("com.cjf.Hello");
		
		Method method = clazz.getMethod("main", new Class[]{String[].class});
		method.invoke(null, (Object)new String[0]);
		
		for (int i = 0; i < bytes.length; i++) {
			System.out.printf("%d:\t %02X \t %c \n",i,bytes[i],(char)bytes[i]);
		}
		
		FileOutputStream fos = new FileOutputStream(new File("Hello.class"));
		fos.write(bytes);
		fos.close();
		
	}
}
 

 

你可能感兴趣的:(java,ASM)