protected HoldingContainer generateEvalBody( ClassGenerator<?> g, HoldingContainer[] inputVariables, String body, JVar[] workspaceJVars) { // g.getBlock().directStatement(String.format("//---- start of eval portion of %s function. // ----//", functionName)); JBlock sub = new JBlock(true, true); JBlock topSub = sub; HoldingContainer out = null; MajorType returnValueType = returnValue.type; // add outside null handling if it is defined. if (nullHandling == NullHandling.NULL_IF_NULL) { JExpression e = null; for (HoldingContainer v : inputVariables) { if (v.isOptional()) { if (e == null) { e = v.getIsSet(); } else { e = e.mul(v.getIsSet()); } } } if (e != null) { // if at least one expression must be checked, set up the conditional. returnValueType = returnValue.type.toBuilder().setMode(DataMode.OPTIONAL).build(); out = g.declare(returnValueType); e = e.eq(JExpr.lit(0)); JConditional jc = sub._if(e); jc._then().assign(out.getIsSet(), JExpr.lit(0)); sub = jc._else(); } } if (out == null) out = g.declare(returnValueType); // add the subblock after the out declaration. g.getEvalBlock().add(topSub); JVar internalOutput = sub.decl( JMod.FINAL, g.getHolderType(returnValueType), returnValue.name, JExpr._new(g.getHolderType(returnValueType))); addProtectedBlock(g, sub, body, inputVariables, workspaceJVars, false); if (sub != topSub) sub.assign(internalOutput.ref("isSet"), JExpr.lit(1)); // Assign null if NULL_IF_NULL mode sub.assign(out.getHolder(), internalOutput); if (sub != topSub) sub.assign(internalOutput.ref("isSet"), JExpr.lit(1)); // Assign null if NULL_IF_NULL mode return out; }
private void genInitFields( Refs r, Map<Ref, JFieldVar> fieldVarMap, JVar viewVar, Collection<Ref> refs, JBlock body) { for (Ref ref : refs) { JFieldVar fieldVar = fieldVarMap.get(ref); JFieldRef idVar = (ref.isAndroidId ? r.androidRClass : r.rClass).staticRef("id").ref(ref.id); if (ref instanceof View) { JClass viewType = r.ref(((View) ref).type); body.assign(fieldVar, cast(viewType, viewVar.invoke("findViewById").arg(idVar))); } else if (ref instanceof Include) { JClass includeType = r.ref(getClassName(((Include) ref).layout)); body.assign(fieldVar, _new(includeType).arg(viewVar)); } } }
@Override public void generate(JDefinedClass cls, GenerationContext context) { if (classSpec.getFields().isEmpty()) { return; // No equals needed. } // Import the objects class, for hash coding. JClass objects = context.getTypeManager().getClassDirect("java.util.Objects"); // Create the equals method. JMethod hashMethod = cls.method(JMod.PUBLIC, int.class, "hashCode"); hashMethod.annotate(Override.class); JBlock body = hashMethod.body(); // Check if the object is null. JVar hash = body.decl(JType.parse(context.getCodeModel(), "int"), "hash", JExpr.lit(3)); // Do check for each field. for (DataFieldSpecification fieldSpec : classSpec.getFields()) { List<String> parts = NameFormat.namesToList(fieldSpec.getFieldName()); String camelCaseFieldName = NameFormat.camelCase(parts, false); // Get the field value. JExpression thisField = JExpr.refthis(camelCaseFieldName); // Accumulate the hash code. JExpression fieldHashCode = objects.staticInvoke("hashCode").arg(thisField); body.assign(hash, JExpr.lit(79).mul(hash).plus(fieldHashCode)); } // Return the processed hash value. body._return(hash); }
private void addConstructors(JDefinedClass jclass, List<String> properties) { // no properties to put in the constructor => default constructor is good enough. if (properties.isEmpty()) { return; } // add a no-args constructor for serialization purposes JMethod noargsConstructor = jclass.constructor(JMod.PUBLIC); noargsConstructor.javadoc().add("No args constructor for use in serialization"); // add the public constructor with property parameters JMethod fieldsConstructor = jclass.constructor(JMod.PUBLIC); JBlock constructorBody = fieldsConstructor.body(); Map<String, JFieldVar> fields = jclass.fields(); for (String property : properties) { JFieldVar field = fields.get(property); if (field == null) { throw new IllegalStateException( "Property " + property + " hasn't been added to JDefinedClass before calling addConstructors"); } fieldsConstructor.javadoc().addParam(property); JVar param = fieldsConstructor.param(field.type(), field.name()); constructorBody.assign(JExpr._this().ref(field), param); } }
@Override public void process(Element element, JCodeModel codeModel, EBeanHolder holder) { Classes classes = holder.classes(); String fieldName = element.getSimpleName().toString(); Res resInnerClass = androidValue.getRInnerClass(); JFieldRef idRef = annotationHelper.extractOneAnnotationFieldRef(holder, element, resInnerClass, true); JBlock methodBody = holder.init.body(); TypeMirror fieldTypeMirror = element.asType(); String fieldType = fieldTypeMirror.toString(); // Special case for loading animations if (CanonicalNameConstants.ANIMATION.equals(fieldType)) { methodBody.assign( ref(fieldName), classes.ANIMATION_UTILS.staticInvoke("loadAnimation").arg(holder.contextRef).arg(idRef)); } else { if (holder.resources == null) { holder.resources = methodBody.decl( classes.RESOURCES, "resources_", holder.contextRef.invoke("getResources")); } String resourceMethodName = androidValue.getResourceMethodName(); // Special case for @HtmlRes if (element.getAnnotation(HtmlRes.class) != null) { methodBody.assign( ref(fieldName), classes .HTML .staticInvoke("fromHtml") .arg(invoke(holder.resources, resourceMethodName).arg(idRef))); } else { methodBody.assign(ref(fieldName), invoke(holder.resources, resourceMethodName).arg(idRef)); } } }
protected void setOnFinishInflate() { onFinishInflate = generatedClass.method(PUBLIC, codeModel().VOID, "onFinishInflate"); onFinishInflate.annotate(Override.class); onFinishInflate.javadoc().append(ALREADY_INFLATED_COMMENT); JBlock ifNotInflated = onFinishInflate.body()._if(getAlreadyInflated().not())._then(); ifNotInflated.assign(getAlreadyInflated(), JExpr.TRUE); getInit(); viewNotifierHelper.invokeViewChanged(ifNotInflated); onFinishInflate.body().invoke(JExpr._super(), "onFinishInflate"); }
@Override public void process(Element element, HasInstanceState holder) { String fieldName = element.getSimpleName().toString(); JBlock saveStateBody = holder.getSaveStateMethodBody(); JVar saveStateBundleParam = holder.getSaveStateBundleParam(); JMethod restoreStateMethod = holder.getRestoreStateMethod(); JBlock restoreStateBody = restoreStateMethod.body(); JVar restoreStateBundleParam = holder.getRestoreStateBundleParam(); AnnotationHelper annotationHelper = new AnnotationHelper(processingEnv); BundleHelper bundleHelper = new BundleHelper(annotationHelper, element); APTCodeModelHelper codeModelHelper = new APTCodeModelHelper(); JFieldRef ref = ref(fieldName); saveStateBody .invoke(saveStateBundleParam, bundleHelper.getMethodNameToSave()) .arg(fieldName) .arg(ref); JInvocation restoreMethodCall = JExpr.invoke(restoreStateBundleParam, bundleHelper.getMethodNameToRestore()).arg(fieldName); if (bundleHelper.restoreCallNeedCastStatement()) { JClass jclass = codeModelHelper.typeMirrorToJClass(element.asType(), holder); JExpression castStatement = JExpr.cast(jclass, restoreMethodCall); restoreStateBody.assign(ref, castStatement); if (bundleHelper.restoreCallNeedsSuppressWarning()) { if (restoreStateMethod.annotations().size() == 0) { restoreStateMethod.annotate(SuppressWarnings.class).param("value", "unchecked"); } } } else { restoreStateBody.assign(ref, restoreMethodCall); } }
private void setter( JCodeModel codeModel, JDefinedClass clazz, JFieldVar field, String fieldName, String remarks) { // setter JMethod setter = clazz.method(JMod.PUBLIC, codeModel.VOID, "set" + fieldName); JVar param = setter.param(field.type(), toFirstCharLower(fieldName)); // メソッド引数 /* Addign java doc for method */ addMethodDoc(setter, remarks + "設定", param); JBlock block2 = setter.body(); block2.assign(JExpr._this().ref(field), param); // ローカル変数からインスタンス変数へセット }
private void convertArguments(JBlock parent, VarArgParser parser) { int index = 0; for (VarArgParser.PositionalArg posArg : parser.getPositionalArguments()) { parent.assign( posArg.getVariable(), convert(posArg.getFormal(), args.component(lit(index++)))); } JForLoop forLoop = parent._for(); JVar loopCounter = forLoop.init(codeModel._ref(int.class), "i", lit(parser.getPositionalArguments().size())); forLoop.test(loopCounter.lt(JExpr.direct("args.length"))); forLoop.update(loopCounter.incr()); forLoop .body() .invoke(parser.getVarArgBuilder(), "add") .arg(argNames.component(loopCounter)) .arg(args.component(loopCounter)); }
private JExpression buildInterceptorChain( JDefinedClass definedClass, ASTMethod method, Map<ASTParameter, JVar> parameterMap, Set<InjectionNode> interceptors, Map<InjectionNode, JFieldVar> interceptorNameMap) { try { JDefinedClass methodExecutionClass = definedClass._class( JMod.PRIVATE | JMod.FINAL, namer.generateClassName(MethodInterceptorChain.MethodExecution.class)); methodExecutionClass._implements(MethodInterceptorChain.MethodExecution.class); // setup constructor with needed parameters JMethod constructor = methodExecutionClass.constructor(JMod.PUBLIC); JBlock constructorbody = constructor.body(); List<JExpression> methodParameters = new ArrayList<JExpression>(); for (ASTParameter parameter : method.getParameters()) { JType parameterType = parameterMap.get(parameter).type(); JVar param = constructor.param(parameterType, namer.generateName(parameterType)); JFieldVar field = methodExecutionClass.field( JMod.PRIVATE, parameterType, namer.generateName(parameterType)); constructorbody.assign(field, param); methodParameters.add(field); } // getMethod() JMethod getMethod = methodExecutionClass.method( JMod.PUBLIC, Method.class, MethodInterceptorChain.MethodExecution.GET_METHOD); JInvocation getMethodInvocation = definedClass.dotclass().invoke(CLASS_GET_METHOD).arg(method.getName()); getMethod.body()._return(getMethodInvocation); getMethod._throws(NoSuchMethodException.class); for (ASTParameter astParameter : method.getParameters()) { getMethodInvocation.arg(codeModel.ref(astParameter.getASTType().getName()).dotclass()); } // invoke() JMethod invokeMethod = methodExecutionClass.method( JMod.PUBLIC, Object.class, MethodInterceptorChain.MethodExecution.INVOKE); // add all throws of contained method for (ASTType throwable : method.getThrowsTypes()) { invokeMethod._throws(codeModel.ref(throwable.getName())); } JInvocation superCall = definedClass.staticRef(SUPER_REF).invoke(method.getName()); for (JExpression methodParam : methodParameters) { superCall.arg(methodParam); } if (method.getReturnType().equals(ASTVoidType.VOID)) { invokeMethod.body().add(superCall); invokeMethod.body()._return(JExpr._null()); } else { invokeMethod.body()._return(superCall); } JInvocation methodExecutionInvocation = JExpr._new(methodExecutionClass); for (ASTParameter astParameter : method.getParameters()) { methodExecutionInvocation.arg(parameterMap.get(astParameter)); } JInvocation newInterceptorInvocation = JExpr._new(codeModel.ref(MethodInterceptorChain.class)) .arg(methodExecutionInvocation) .arg(JExpr._this()); for (InjectionNode interceptor : interceptors) { newInterceptorInvocation.arg(interceptorNameMap.get(interceptor)); } return newInterceptorInvocation; } catch (JClassAlreadyExistsException e) { throw new TransfuseAnalysisException("Class already defined while generating inner class", e); } }
private void buildMethodInterceptor( JDefinedClass definedClass, ConstructorInjectionPoint proxyConstructorInjectionPoint, JMethod constructor, JBlock constructorBody, Map<ASTMethod, Map<InjectionNode, JFieldVar>> interceptorFields, Map.Entry<ASTMethod, Set<InjectionNode>> methodInterceptorEntry) throws ClassNotFoundException { ASTMethod method = methodInterceptorEntry.getKey(); if (method.getAccessModifier().equals(ASTAccessModifier.PRIVATE)) { throw new TransfuseAnalysisException("Unable to provide AOP on private methods"); } if (!interceptorFields.containsKey(methodInterceptorEntry.getKey())) { interceptorFields.put( methodInterceptorEntry.getKey(), new HashMap<InjectionNode, JFieldVar>()); } Map<InjectionNode, JFieldVar> injectionNodeInstanceNameMap = interceptorFields.get(methodInterceptorEntry.getKey()); // setup interceptor fields for (InjectionNode interceptorInjectionNode : methodInterceptorEntry.getValue()) { String interceptorInstanceName = namer.generateName(interceptorInjectionNode); JFieldVar interceptorField = definedClass.field( JMod.PRIVATE, codeModel.ref(interceptorInjectionNode.getClassName()), interceptorInstanceName); injectionNodeInstanceNameMap.put(interceptorInjectionNode, interceptorField); JVar interceptorParam = constructor.param( codeModel.ref(interceptorInjectionNode.getClassName()), namer.generateName(interceptorInjectionNode)); constructorBody.assign(interceptorField, interceptorParam); proxyConstructorInjectionPoint.addInjectionNode(interceptorInjectionNode); } JType returnType = codeModel.parseType(method.getReturnType().getName()); JMethod methodDeclaration = definedClass.method( method.getAccessModifier().getCodeModelJMod(), returnType, method.getName()); JBlock body = methodDeclaration.body(); // define method parameter Map<ASTParameter, JVar> parameterMap = new HashMap<ASTParameter, JVar>(); for (ASTParameter parameter : method.getParameters()) { parameterMap.put( parameter, methodDeclaration.param( JMod.FINAL, codeModel.ref(parameter.getASTType().getName()), namer.generateName(parameter.getASTType()))); } // aop interceptor Map<InjectionNode, JFieldVar> interceptorNameMap = interceptorFields.get(methodInterceptorEntry.getKey()); JArray paramArray = JExpr.newArray(codeModel.ref(Object.class)); for (ASTParameter astParameter : method.getParameters()) { paramArray.add(parameterMap.get(astParameter)); } JInvocation interceptorInvocation = buildInterceptorChain( definedClass, method, parameterMap, methodInterceptorEntry.getValue(), interceptorNameMap) .invoke("invoke"); interceptorInvocation.arg(paramArray); if (method.getReturnType().equals(ASTVoidType.VOID)) { body.add(interceptorInvocation); } else { body._return(JExpr.cast(returnType.boxify(), interceptorInvocation)); } }