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?