import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.Method;
public class ReflectASMExample {
public static void main(String[] args) throws Exception {
ClassWriter cw = new ClassWriter(0);
cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, "ReflectASMExample", null, Type.getInternalName(Object.class), null);
MethodVisitor constructor = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
constructor.visitVarInsn(Opcodes.ALOAD, 0);
constructor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Object.class), "<init>", "()V", false);
constructor.visitInsn(Opcodes.RETURN);
constructor.visitMaxs(1, 1);
constructor.visitEnd();
MethodVisitor method = cw.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, "sayHello", "()V", null, null);
method.visitFieldInsn(Opcodes.GETSTATIC, Type.getInternalName(System.class), "out", Type.getDescriptor(PrintStream.class));
method.visitLdcInsn("Hello ReflectASM!");
method.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(PrintStream.class), "println", "(Ljava/lang/String;)V", false);
method.visitInsn(Opcodes.RETURN);
method.visitMaxs(2, 0);
method.visitEnd();
byte[] classData = cw.toByteArray();
ClassLoader classLoader = new ClassLoader() {
protected Class<?> findClass(String name) throws ClassNotFoundException {
if (name.equals("ReflectASMExample")) {
return defineClass(name, classData, 0, classData.length);
}
return super.findClass(name);
}
};
Class<?> clazz = classLoader.loadClass("ReflectASMExample");
Object instance = clazz.newInstance();
Method sayHelloMethod = clazz.getDeclaredMethod("sayHello");
sayHelloMethod.invoke(instance);
}
}