* of this class is instantiated, and code is generated
* that will copy all of the CMP fields from the EJB
* into the primary key instance.
*/
private void createSimplePrimaryKeyGetter() {
final MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "OpenEJB_getPrimaryKey", "()Ljava/lang/Object;", null, null);
mv.visitCode();
// the primary key is identifed as a field. We just return that value directly.
if (pkField != null) {
// push the pk field
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, implClassName, pkField.getName(), pkField.getDescriptor());
// return the pk field (from the stack)
mv.visitInsn(pkField.getType().getOpcode(IRETURN));
} else if (Object.class.equals(primKeyClass)) {
// this is a container-generated primary key. It's a long value stored in
// a generated field. We return that value, wrappered in a Long instance.
// push the pk field
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, implClassName, UNKNOWN_PK_NAME, UNKNOWN_PK_TYPE.getDescriptor());
// return the pk field (from the stack)
mv.visitInsn(UNKNOWN_PK_TYPE.getOpcode(IRETURN));
} else {
// We have a primary key class defined. For every field that matches one of the
// defined CMP fields, we generate code to copy that value into the corresponding
// field of the primary key class.
final String pkImplName = primKeyClass.getName().replace('.', '/');
// new Pk();
mv.visitTypeInsn(NEW, pkImplName);
mv.visitInsn(DUP);
mv.visitMethodInsn(INVOKESPECIAL, pkImplName, "<init>", "()V", false);
mv.visitVarInsn(ASTORE, 1);
mv.visitVarInsn(ALOAD, 1);
// copy each field from the ejb to the pk class
for (final Field field : primKeyClass.getFields()) {
final CmpField cmpField = cmpFields.get(field.getName());
// only process the cmp fields
if (cmpField == null) {
continue;
}
// verify types match... this should have been caught by the verifier, but
// check again since generated code is so hard to debug
if (!cmpField.getType().getClassName().equals(field.getType().getName())) {
throw new IllegalArgumentException("Primary key " + cmpField.getName() + " is type " + cmpField.getType().getClassName() + " but CMP field is type " + field.getType().getName());
}
// push the value from the cmp bean
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, implClassName, cmpField.getName(), cmpField.getDescriptor());
// set matching field in the pk class to the value on the stack
mv.visitFieldInsn(PUTFIELD, pkImplName, cmpField.getName(), cmpField.getDescriptor());
mv.visitVarInsn(ALOAD, 1);
}
// return the Pk();
mv.visitInsn(ARETURN);
}
mv.visitMaxs(0, 0);
mv.visitEnd();
}