* @throws NotFoundException
*/
private void addProducerMethod(Field field, CtClass mainClass) throws ClassNotFoundException,
CannotCompileException, NotFoundException, IOException {
CtMethod mnew = null;
String injectedFieldType = field.getType().getName();
String injectedFieldName = field.getName();
if (producerMethodKeys.contains(injectedFieldType + injectedFieldName)) {
return;
} else {
producerMethodKeys.add(injectedFieldType + injectedFieldName);
}
// construct producer method body
StringBuilder sb = new StringBuilder();
sb.append("public ");
sb.append(injectedFieldType);
sb.append(" get");
sb.append(injectedFieldName);
sb.append("() {");
sb.append(injectedFieldType + " f = null;");
sb.append("Component c = ZkCDIIntegrationContext.getContextComponent();");
// sb.append("System.out.println(\"Current thread id = \" + Thread.currentThread().getId());");
sb.append("if(c == null) {");
// sb.append("System.out.println(\"returning dummy instance of " + injectedFieldType + "\");");
sb.append("return new " + injectedFieldType + "();} else {");
// sb.append("System.out.println(\"returning component retrieved from component tree\" + c);");
sb.append("try {");
sb.append("f = (" + injectedFieldType + ")c.getFellow(\""
+ injectedFieldName + "\");");
// sb.append("System.out.println(\"returning component retrieved from component tree\" + f);");
sb.append("}catch(ComponentNotFoundException e) {e.printStackTrace(); throw new RuntimeException(e.getMessage());}}");
sb.append("return f;");
sb.append("}");
mnew = CtNewMethod.make(sb.toString(), mainClass);
ConstPool cp = mnew.getMethodInfo().getConstPool();
AnnotationsAttribute attr = new AnnotationsAttribute(cp,
AnnotationsAttribute.visibleTag);
javassist.bytecode.annotation.Annotation producesAnnotation = new javassist.bytecode.annotation.Annotation(
"javax.enterprise.inject.Produces", cp);
javassist.bytecode.annotation.Annotation zkScopedAnnotation = new javassist.bytecode.annotation.Annotation(
"org.zkoss.cdi.context.IdSpaceScoped", cp);
javassist.bytecode.annotation.Annotation zkCompAnnotation = new javassist.bytecode.annotation.Annotation(
"org.zkoss.cdi.inject.ComponentId", cp);
zkCompAnnotation.addMemberValue("value", new StringMemberValue(field
.getName(), cp));
attr.addAnnotation(producesAnnotation);
attr.addAnnotation(zkScopedAnnotation);
attr.addAnnotation(zkCompAnnotation);
mnew.getMethodInfo().addAttribute(attr);
mainClass.addMethod(mnew);
}