0

I am starting to use asm for generating classes at runtime. I started with a very simple class, which has just one String field and a getter for the same.

ClassWriter cw = new ClassWriter(0);
String Name = "Sample";
            cw.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC ,
                    Name, null,"java/lang/Object",
                    new String[] {});
                    cw.visitField(Opcodes.ACC_PRIVATE, "punit", "Ljava/lang/String;",
                    null, "sac").visitEnd();
            MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "getUnit",
                    "()Ljava/lang/String;", null, null);

            mv.visitCode();
            mv.visitVarInsn(Opcodes.ALOAD, 0);
            mv.visitFieldInsn(Opcodes.GETFIELD, destinationName+"Configuration", "unit", "Ljava/lang/String;");
            mv.visitInsn(Opcodes.ARETURN);
            mv.visitMaxs(1, 1);
            mv.visitEnd();           
            cw.visitEnd();

            byte[] b = cw.toByteArray();

After the byte array is created I create a custom classLoader & called its defineClass method to get hold of the Class object.

Then I call newInstance() on this object but I get an InstantiationException. When I debugged the code I found that it is not finding a constructor for the newly created class!

Should I generate a constructor for the class as well?

Sachin C Nambiar
  • 135
  • 2
  • 11
  • 1
    `Should I generate a constructor for the class as well?`---yes, you should. `javac` generates it automatically for any class defined by source code, but you aren't using a Java compiler to generate this class. – Marko Topolnik Aug 16 '15 at 11:26
  • @MarkoTopolnik Thank you:) It solved my problem. – Sachin C Nambiar Aug 16 '15 at 17:17

0 Answers0