Java Magazine, July/August 2018
ORACLE COM JAVAMAGAZINE JULY AUGUST 2018 41 libraries mv visitInsn RETURN mv visitMaxs 1 1 mv visitEnd This code works with a MethodVisitor that is created from the ClassWriter field before visiting each instruction in turn After that you must finish the method by noting how many stack slots the code uses You do this by calling visitMaxs The main method is added using another MethodVisitor void addMainMethod MethodVisitor mv cw visitMethod ACC_ PUBLIC ACC_ STATIC main Ljava lang String V null null mv visitCode 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 false mv visitInsn RETURN mv visitMaxs 3 3 mv visitEnd The code here is a little more complex because objects need to be retrieved from static fields via a GETSTATIC opcode and then the method must be called When I run MakeHelloWorld I see HelloWorld class appear in the file system I can run the generated class in the usual way java HelloWorld and when I do I see the familiar message appear
You must have JavaScript enabled to view digital editions.