Re: Creating class using ASM

Rémi Forax <[email protected]>
Newsgroups gmane.comp.java.objectweb.asm
Message-ID <[email protected]>
On 03/21/2011 01:27 AM, [email protected] wrote:
> at beginning i was planning to create easy class, something like :
> class myClass{
> public static void main(String arg[])
> {
> System.out.println(1);
> }
> }
>
> based on tutorial what i founded i wrote  code:
> ClassWriter cw = new ClassWriter(0);
> cw.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC +Opcodes.ACC_SUPER,
> 		    "myClass",	  // class name
> 		    null,
> 		    "java/lang/Object",
> 		    null);   // source file
>
> MethodVisitor mvc = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null,
> null);
> mvc.visitVarInsn    (Opcodes.ALOAD, 0);
> mvc.visitMethodInsn (Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>",
> "()V");
> 		mvc.visitInsn	    (Opcodes.RETURN);
> 		mvc.visitEnd();
> 		
> MethodVisitor mv = cw.visitMethod( Opcodes.ACC_PUBLIC+Opcodes.ACC_STATIC,
> 		    "main",		   // method name
> 		    "(Ljava/lang/String[];)V", // method descriptor
> 		    null,		     // exceptions
> 		    null);		     // method attributes
> mv.visitCode();
> mv.visitFieldInsn  (Opcodes.GETSTATIC, "java/lang/System", "out",
> "Ljava/io/PrintStream;");
> mv.visitInsn(Opcodes.ICONST_1);
> mv.visitMethodInsn (Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println",
> "(I)V");
> mv.visitInsn	   (Opcodes.RETURN);
> mv.visitEnd();
> cw.visitEnd();
> byte[] bytecode = cw.toByteArray();
>
> which is not working, but after i disasseble both classes, i got almost same
> code for both of them:
> public class myClass extends java.lang.Object{
>
> public myClass();
>    Code:
>     0:	aload_0
>     1:	invokespecial	#8; //Method java/lang/Object."<init>":()V
>     4:	return
> public static void main(java.lang.String[]);
>    Code:
>     0:	getstatic	#16; //Field java/lang/System.out:Ljava/io/PrintStream;
>     3:	iconst_1
>     4:	invokevirtual	#22; //Method java/io/PrintStream.println:(I)V
>     7:	return
> }
>
> where in my class made from source i have #1 #2 #3 instead of #8 #16 #22
>
> and error message when i'm trying run my class is:
> Arguments can't fit into locals in class file myClass
> can anyone tell me what i'm doing wrong
> regards

You forget to call mv.visitMax() before mv.visitEnd().

Rémi
message-footer.txt (text/plain, 238 B)
-- 
You receive this message as a subscriber of the [email protected] mailing list.
To unsubscribe: mailto:[email protected]
For general help: mailto:[email protected]?subject=help
OW2 mailing lists service home page: http://www.ow2.org/wws
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.