本文整理了Java中com.sun.codemodel.JBlock
类的一些代码示例,展示了JBlock
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。JBlock
类的具体详情如下:
包路径:com.sun.codemodel.JBlock
类名称:JBlock
[英]A block of Java code, which may contain statements and local declarations.
JBlock contains a large number of factory methods that creates new statements/declarations. Those newly created statements/declarations are inserted into the #pos(). The position advances one every time you add a new instruction.
[中]Java代码块,其中可能包含语句和本地声明。
JBlock包含大量创建新语句/声明的工厂方法。这些新创建的语句/声明将插入到#pos()中。每次添加新指令时,该位置将前进一步。
代码示例来源:origin: joelittlejohn/jsonschema2pojo
private void addFactoryMethod(JDefinedClass _enum, JType backingType) {
JFieldVar quickLookupMap = addQuickLookupMap(_enum, backingType);
JMethod fromValue = _enum.method(JMod.PUBLIC | JMod.STATIC, _enum, "fromValue");
JVar valueParam = fromValue.param(backingType, "value");
JBlock body = fromValue.body();
JVar constant = body.decl(_enum, "constant");
constant.init(quickLookupMap.invoke("get").arg(valueParam));
JConditional _if = body._if(constant.eq(JExpr._null()));
JInvocation illegalArgumentException = JExpr._new(_enum.owner().ref(IllegalArgumentException.class));
JExpression expr = valueParam;
// if string no need to add ""
if(!isString(backingType)){
expr = expr.plus(JExpr.lit(""));
}
illegalArgumentException.arg(expr);
_if._then()._throw(illegalArgumentException);
_if._else()._return(constant);
ruleFactory.getAnnotator().enumCreatorMethod(_enum, fromValue);
}
代码示例来源:origin: joelittlejohn/jsonschema2pojo
private void addHashCode(JDefinedClass jclass, JsonNode node) {
Map<String, JFieldVar> fields = removeFieldsExcludedFromEqualsAndHashCode(jclass.fields(), node);
JMethod hashCode = jclass.method(JMod.PUBLIC, int.class, "hashCode");
JBlock body = hashCode.body();
JVar result = body.decl(jclass.owner().INT, "result", JExpr.lit(1));
JFieldRef fieldRef = JExpr.refthis(fieldVar.name());
fieldHash = JExpr.cast(jclass.owner().INT, fieldRef.xor(fieldRef.shrz(JExpr.lit(32))));
} else if ("boolean".equals(fieldVar.type().name())) {
fieldHash = JOp.cond(fieldRef, JExpr.lit(1), JExpr.lit(0));
fieldHash = jclass.owner().ref(Arrays.class).staticInvoke("hashCode").arg(fieldRef);
} else {
fieldHash = JOp.cond(fieldRef.eq(JExpr._null()), JExpr.lit(0), fieldRef.invoke("hashCode"));
body.assign(result, result.mul(JExpr.lit(31)).plus(fieldHash));
if (!jclass._extends().fullName().equals(Object.class.getName())) {
body.assign(result, result.mul(JExpr.lit(31)).plus(JExpr._super().invoke("hashCode")));
body._return(result);
hashCode.annotate(Override.class);
代码示例来源:origin: joelittlejohn/jsonschema2pojo
private void addOverrideBuilder(JDefinedClass thisJDefinedClass, JMethod parentBuilder, JVar parentParam) {
if (thisJDefinedClass.getMethod(parentBuilder.name(), new JType[] {parentParam.type()}) == null) {
JMethod builder = thisJDefinedClass.method(parentBuilder.mods().getValue(), thisJDefinedClass, parentBuilder.name());
builder.annotate(Override.class);
JVar param = builder.param(parentParam.type(), parentParam.name());
JBlock body = builder.body();
body.invoke(JExpr._super(), parentBuilder).arg(param);
body._return(JExpr._this());
}
}
}
代码示例来源:origin: joelittlejohn/jsonschema2pojo
private void addBuilder(JDefinedClass jclass, JType propertyType, JFieldVar field) {
JMethod builder = jclass.method(JMod.PUBLIC, jclass, "withAdditionalProperty");
JVar nameParam = builder.param(String.class, "name");
JVar valueParam = builder.param(propertyType, "value");
JBlock body = builder.body();
JInvocation mapInvocation = body.invoke(JExpr._this().ref(field), "put");
mapInvocation.arg(nameParam);
mapInvocation.arg(valueParam);
body._return(JExpr._this());
}
代码示例来源:origin: joelittlejohn/jsonschema2pojo
private JMethod addPublicGetMethod(JDefinedClass jclass, JMethod internalGetMethod, JFieldRef notFoundValue) {
JMethod method = jclass.method(PUBLIC, jclass.owner()._ref(Object.class), GETTER_NAME);
JTypeVar returnType = method.generify("T");
method.type(returnType);
Models.suppressWarnings(method, "unchecked");
JVar nameParam = method.param(String.class, "name");
JBlock body = method.body();
JVar valueVar = body.decl(jclass.owner()._ref(Object.class), "value",
invoke(internalGetMethod).arg(nameParam).arg(notFoundValue));
JConditional found = method.body()._if(notFoundValue.ne(valueVar));
found._then()._return(cast(returnType, valueVar));
JBlock notFound = found._else();
JMethod getAdditionalProperties = jclass.getMethod("getAdditionalProperties", new JType[] {});
if (getAdditionalProperties != null) {
notFound._return(cast(returnType, invoke(getAdditionalProperties).invoke("get").arg(nameParam)));
} else {
notFound._throw(illegalArgumentInvocation(jclass, nameParam));
}
return method;
}
代码示例来源:origin: joelittlejohn/jsonschema2pojo
JClass stringBuilderClass = jclass.owner().ref(StringBuilder.class);
JVar sb = body.decl(stringBuilderClass, "sb", JExpr._new(stringBuilderClass));
body.add(sb
.invoke("append").arg(jclass.dotclass().invoke("getName"))
.invoke("append").arg(JExpr.lit('@'))
.invoke("append").arg(
jclass.owner().ref(Integer.class).staticInvoke("toHexString").arg(
jclass.owner().ref(System.class).staticInvoke("identityHashCode").arg(JExpr._this())))
JVar baseLength = body.decl(jclass.owner().INT, "baseLength", sb.invoke("length"));
JVar superString = body.decl(jclass.owner().ref(String.class), "superString", JExpr._super().invoke("toString"));
JBlock superToStringBlock = body._if(superString.ne(JExpr._null()))._then();
JVar contentStart = superToStringBlock.decl(jclass.owner().INT, "contentStart",
superString.invoke("indexOf").arg(JExpr.lit('[')));
JVar contentEnd = superToStringBlock.decl(jclass.owner().INT, "contentEnd",
JConditional superToStringInnerConditional = superToStringBlock._if(
superToStringInnerConditional._then().add(
superToStringInnerConditional._else().add(sb.invoke("append").arg(superString));
body._if(sb.invoke("length").gt(baseLength))
._then().add(sb.invoke("append").arg(JExpr.lit(',')));
body.add(sb.invoke("append").arg(fieldVar.name()));
代码示例来源:origin: joelittlejohn/jsonschema2pojo
private void addEquals(JDefinedClass jclass, JsonNode node) {
Map<String, JFieldVar> fields = removeFieldsExcludedFromEqualsAndHashCode(jclass.fields(), node);
JMethod equals = jclass.method(JMod.PUBLIC, boolean.class, "equals");
JVar otherObject = equals.param(Object.class, "other");
JBlock body = equals.body();
body._if(otherObject.eq(JExpr._this()))._then()._return(JExpr.TRUE);
body._if(otherObject._instanceof(jclass).eq(JExpr.FALSE))._then()._return(JExpr.FALSE);
JVar rhsVar = body.decl(jclass, "rhs").init(JExpr.cast(jclass, otherObject));
JExpression result = JExpr.lit(true);
if (!jclass._extends().fullName().equals(Object.class.getName())) {
result = result.cand(JExpr._super().invoke("equals").arg(rhsVar));
fieldEquals = jclass.owner().ref(Arrays.class).staticInvoke("equals").arg(thisFieldRef).arg(otherFieldRef);
} else {
fieldEquals = thisFieldRef.eq(otherFieldRef).cor(
body._return(result);
equals.annotate(Override.class);
代码示例来源:origin: bonitasoft/bonita-engine
public JMethod addListSetter(final JDefinedClass definedClass, final JFieldVar field) {
final JMethod method = definedClass.method(JMod.PUBLIC, Void.TYPE, getSetterName(field));
method.param(field.type(), field.name());
final JFieldRef thisField = JExpr._this().ref(field.name());
final JConditional ifListIsNull = method.body()._if(thisField.eq(JExpr._null()));
ifListIsNull._then().assign(JExpr._this().ref(field.name()), JExpr.ref(field.name()));
final JBlock elseBlock = ifListIsNull._else();
final JVar copyVar = elseBlock.decl(field.type(), "copy", JExpr._new(getModel().ref(ArrayList.class)).arg(field));
elseBlock.invoke(JExpr._this().ref(field.name()), "clear");
elseBlock.invoke(JExpr._this().ref(field.name()), "addAll").arg(copyVar);
return method;
}
代码示例来源:origin: joelittlejohn/jsonschema2pojo
private JMethod addPublicWithMethod(JDefinedClass jclass, JMethod internalSetMethod) {
JMethod method = jclass.method(PUBLIC, jclass, BUILDER_NAME);
JVar nameParam = method.param(String.class, "name");
JVar valueParam = method.param(Object.class, "value");
JBlock body = method.body();
JBlock notFound = body._if(JOp.not(invoke(internalSetMethod).arg(nameParam).arg(valueParam)))._then();
// if we have additional properties, then put value.
JMethod getAdditionalProperties = jclass.getMethod("getAdditionalProperties", new JType[] {});
if (getAdditionalProperties != null) {
JType additionalPropertiesType = ((JClass) (getAdditionalProperties.type())).getTypeParameters().get(1);
notFound.add(invoke(getAdditionalProperties).invoke("put").arg(nameParam)
.arg(cast(additionalPropertiesType, valueParam)));
}
// else throw exception.
else {
notFound._throw(illegalArgumentInvocation(jclass, nameParam));
}
body._return(_this());
return method;
}
代码示例来源:origin: joelittlejohn/jsonschema2pojo
private JMethod addInternalGetMethodJava6(JDefinedClass jclass, JsonNode propertiesNode) {
JMethod method = jclass.method(PROTECTED, jclass.owner()._ref(Object.class), DEFINED_GETTER_NAME);
JVar nameParam = method.param(String.class, "name");
JVar notFoundParam = method.param(jclass.owner()._ref(Object.class), "notFoundValue");
JBlock body = method.body();
JConditional propertyConditional = null;
JType propertyType = jclass.fields().get(fieldName).type();
JExpression condition = lit(propertyName).invoke("equals").arg(nameParam);
if (propertyConditional == null) {
propertyConditional = body._if(condition);
} else {
propertyConditional = propertyConditional._elseif(condition);
JMethod propertyGetter = jclass.getMethod(getGetterName(propertyName, propertyType, node), new JType[] {});
propertyConditional._then()._return(invoke(propertyGetter));
JDefinedClass parentClass = (JDefinedClass) extendsType;
JMethod parentMethod = parentClass.getMethod(DEFINED_GETTER_NAME,
new JType[] { parentClass.owner()._ref(String.class), parentClass.owner()._ref(Object.class) });
lastBlock._return(_super().invoke(parentMethod).arg(nameParam).arg(notFoundParam));
} else {
lastBlock._return(notFoundParam);
代码示例来源:origin: e-biz/androidkickstartr
jClass._extends(ref.fragmentPagerAdapter());
if (hasLocationsField) {
locationsField = jClass.field(JMod.PRIVATE, ref.string().array(), "locations");
constructorBody.directStatement("super(fm);");
constructorBody.assign(JExpr._this().ref("locations"), locationsField);
getCountMethodBody._return(locationsField.ref("length"));
} else {
getCountMethodBody.directStatement("return 3;");
JVar fragmentVar = getItemMethodBody.decl(ref.fragment(), "fragment", JExpr._new(ref.ref(sampleFragmentPackage)));
JVar bundleVar = getItemMethodBody.decl(ref.bundle(), "bundle", JExpr._new(ref.bundle()));
getItemMethodBody.directStatement("bundle.putString(\"label\", locations[position]);");
} else {
getItemMethodBody.directStatement("bundle.putString(\"label\", \"LABEL \" + position);");
getItemMethodBody.invoke(fragmentVar, "setArguments").arg(bundleVar);
getItemMethodBody._return(fragmentVar);
代码示例来源:origin: org.jvnet.jaxbvalidation/jaxbvalidation-core
public JStatement validate(final DatabindableDatatype datatype, final JCodeModel codeModel, final JDefinedClass theClass, final JExpression value, final JAssignmentTarget problem)
{
final JBlock block = newBlock();
final JConditional ifValueIsNmtoken = block._if(codeModel.ref(XmlNames.class).staticInvoke("isNmtoken").arg(value));
ifValueIsNmtoken._then().directStatement("// Value is a valid Nmtoken");
ifValueIsNmtoken._else().
assign(problem, JExpr._new(codeModel.ref(NmtokenProblem.class)).arg(value));
return block;
}
}
代码示例来源:origin: joelittlejohn/jsonschema2pojo
private JMethod addInternalSetMethodJava7(JDefinedClass jclass, JsonNode propertiesNode) {
JMethod method = jclass.method(PROTECTED, jclass.owner().BOOLEAN, DEFINED_SETTER_NAME);
JVar nameParam = method.param(String.class, "name");
JVar valueParam = method.param(Object.class, "value");
JBlock body = method.body();
JSwitch propertySwitch = body._switch(nameParam);
if (propertiesNode != null) {
for (Iterator<Map.Entry<String, JsonNode>> properties = propertiesNode.fields(); properties.hasNext();) {
Map.Entry<String, JsonNode> property = properties.next();
String propertyName = property.getKey();
JsonNode node = property.getValue();
String fieldName = ruleFactory.getNameHelper().getPropertyName(propertyName, node);
JType propertyType = jclass.fields().get(fieldName).type();
addSetPropertyCase(jclass, propertySwitch, propertyName, propertyType, valueParam, node);
}
}
JBlock defaultBlock = propertySwitch._default().body();
JClass extendsType = jclass._extends();
if (extendsType != null && extendsType instanceof JDefinedClass) {
JDefinedClass parentClass = (JDefinedClass) extendsType;
JMethod parentMethod = parentClass.getMethod(DEFINED_SETTER_NAME,
new JType[] { parentClass.owner()._ref(String.class), parentClass.owner()._ref(Object.class) });
defaultBlock._return(_super().invoke(parentMethod).arg(nameParam).arg(valueParam));
} else {
defaultBlock._return(FALSE);
}
return method;
}
代码示例来源:origin: io.konig/konig-schemagen
private void generateCurieMethod(JCodeModel model, JDefinedClass dc, JVar mapField) {
JClass stringBuilderClass = model.ref(StringBuilder.class);
JClass namespaceClass = model.ref(Namespace.class);
JMethod method = dc.method(JMod.PUBLIC | JMod.STATIC, String.class, "curie");
JVar uriVar = method.param(URI.class, "uri");
JVar nsVar = method.body().decl(namespaceClass, "ns", mapField.invoke("get").arg(uriVar.invoke("getNamespace")));
method.body()._if(JOp.eq(nsVar, JExpr._null()))._then()._return(uriVar.invoke("stringValue"));
JVar builderVar = method.body().decl(stringBuilderClass, "builder", JExpr._new(stringBuilderClass));
method.body().add(builderVar.invoke("add").arg(nsVar.invoke("getPrefix")));
method.body().add(builderVar.invoke("add").arg(JExpr.lit(':')));
method.body().add(builderVar.invoke("add").arg(uriVar.invoke("getLocalName")));
method.body()._return(builderVar.invoke("toString"));
}
代码示例来源:origin: bonitasoft/bonita-engine
private JMethod addListMethod(final JDefinedClass definedClass, final Field field, final String listMethodName, final String parameterName) {
final JClass fieldClass = toJavaClass(field);
final StringBuilder builder = new StringBuilder(parameterName);
builder.append(WordUtils.capitalize(field.getName()));
final JMethod method = definedClass.method(JMod.PUBLIC, void.class, builder.toString());
final JVar adderParam = method.param(fieldClass, parameterName);
final JBlock body = method.body();
final JVar decl = body.decl(getModel().ref(List.class), field.getName(), JExpr.invoke(getGetterName(field)));
body.add(decl.invoke(listMethodName).arg(adderParam));
return method;
}
代码示例来源:origin: apache/drill
JBlock sub = new JBlock(true, true);
sub.assign(workspaceJVars[3].component(JExpr.lit(i)), workspaceJVars[2].component(JExpr.lit(i)));
JBlock conditionalBlock = new JBlock(false, false);
JConditional jc = conditionalBlock._if(inputVariables[i].getIsSet().ne(JExpr.lit(0)));
jc._then().assign(JExpr.ref(workspaceJVars[3].component(JExpr.lit(i)), "valueHolder"), inputVariables[i].getHolder());
jc._else().assign(JExpr.ref(workspaceJVars[3].component(JExpr.lit(i)), "valueHolder"), JExpr._null());
sub.add(conditionalBlock);
} else {
sub.assign(workspaceJVars[3].component(JExpr.lit(i)), workspaceJVars[2].component(JExpr.lit(i)));
sub.assign(JExpr.ref(workspaceJVars[3].component(JExpr.lit(i)), "valueHolder"), inputVariables[i].getHolder());
JVar retVal = sub.decl(m._ref(Object.class), "ret");
JTryBlock udfEvalTry = sub._try();
udfEvalTry.body().assign(retVal,
workspaceJVars[1].invoke("evaluate").arg(workspaceJVars[3]));
JCatchBlock udfEvalCatch = udfEvalTry._catch(m.directClass(Exception.class.getCanonicalName()));
JVar exVar = udfEvalCatch.param("ex");
udfEvalCatch.body()
._throw(JExpr._new(m.directClass(RuntimeException.class.getCanonicalName()))
.arg(JExpr.lit(String.format("GenericUDF.evaluate method failed"))).arg(exVar));
sub.add(ObjectInspectorHelper.getDrillObject(m, returnOI, workspaceJVars[0], workspaceJVars[4], retVal));
sub.assign(out.getHolder(), workspaceJVars[4]);
setup.directStatement(String.format("/** start %s for function %s **/ ",
ClassGenerator.BlockType.EVAL.name(), genericUdfClazz.getName() + (!isGenericUDF ? "("+udfName+")" : "")));
代码示例来源:origin: joelittlejohn/jsonschema2pojo
public void addConstructorFromParcel(JDefinedClass jclass) {
JMethod ctorFromParcel = jclass.constructor(JMod.PROTECTED);
JVar in = ctorFromParcel.param(jclass.owner().directClass("android.os.Parcel"), "in");
if (extendsParcelable(jclass)) {
ctorFromParcel.body().directStatement("super(in);");
}
for (JFieldVar f : jclass.fields().values()) {
if( (f.mods().getValue() & JMod.STATIC) == JMod.STATIC ) {
continue;
}
if (f.type().erasure().name().equals("List")) {
ctorFromParcel.body()
.invoke(in, "readList")
.arg(JExpr._this().ref(f))
.arg(JExpr.direct(getListType(f.type()) + ".class.getClassLoader()"));
} else {
ctorFromParcel.body().assign(
JExpr._this().ref(f),
JExpr.cast(
f.type(),
in.invoke("readValue").arg(JExpr.direct(f.type().erasure().name() + ".class.getClassLoader()"))
)
);
}
}
}
代码示例来源:origin: e-biz/androidkickstartr
private void addListNavigationConfiguration(JBlock configureActionBarBody) {
jClass._implements(ref.sNavigationListener());
JBlock onNavigationItemSelectedBody = onNavigationItemSelectedMethod.body();
if (appDetails.isViewPager()) {
onNavigationItemSelectedBody.invoke(pagerField, "setCurrentItem").arg(itemPositionParam);
onNavigationItemSelectedBody._return(JExpr.TRUE);
JInvocation getSupportActionbar = JExpr.invoke("getSupportActionBar");
JInvocation getContext = getSupportActionbar.invoke("getThemedContext");
JVar contextVar = configureActionBarBody.decl(ref.context(), "context", getContext);
JExpression rLayoutSherlockSpinner = JExpr.direct("android.R.layout.simple_list_item_1");
arg(contextVar). //
arg(rArrayLocations). //
arg(rLayoutSherlockSpinner);
JVar listVar = configureActionBarBody.decl(listType, "list", createFromResource);
configureActionBarBody.invoke(getSupportActionbar, "setNavigationMode").arg(navigationModeList);
configureActionBarBody.invoke(getSupportActionbar, "setListNavigationCallbacks").//
arg(listVar).//
arg(JExpr._this());
代码示例来源:origin: e-biz/androidkickstartr
jClass = jCodeModel._class(appDetails.getSampleFragmentPackage());
jClass._extends(ref.ref(appDetails.getRoboSherlockFragmentPackage()));
} else if (appDetails.isRoboguice()) {
jClass._extends(ref.roboFragment());
} else {
jClass._extends(ref.fragment());
JMethod onCreateViewMethod = jClass.method(JMod.NONE, jCodeModel.VOID, "afterViews");
onCreateViewMethod.annotate(ref.afterViews());
onCreateViewMethodBody = onCreateViewMethod.body();
JMethod onCreateViewMethod = jClass.method(JMod.PUBLIC, ref.view(), "onCreateView");
onCreateViewMethod.annotate(ref.override());
JVar inflaterParam = onCreateViewMethod.param(ref.layoutInflater(), "inflater");
JVar containerParam = onCreateViewMethod.param(ref.viewGroup(), "container");
onCreateViewMethodBody = onCreateViewMethod.body();
onCreateViewMethodBody._return(inflateView(inflaterParam, containerParam));
onViewCreatedMethodBody.invoke(JExpr._super(), "onViewCreated").arg(viewParam).arg(savedInstanceStateParam);
JVar contentViewVar = onCreateViewMethodBody.decl(ref.view(), "contentView", inflateInvoke);
onCreateViewMethodBody._return(contentViewVar);
代码示例来源:origin: fusesource/fuse-extra
private void generateToString() {
toString = cls().method(JMod.PUBLIC, cm.ref("java.lang.String"), "toString");
toString.body()._return(ref("this").invoke("toString").arg(lit("")));
JMethod toString2 = cls().method(JMod.PUBLIC, cm.ref("java.lang.String"), "toString");
toString2.param(String.class, "indent");
toString2.body()._if(_this().ref("value").eq(_null()))._then().block()._return(lit("null"));
if ( type.getName().equals("array") ) {
toString2.body()._return(cm.ref("java.util.Arrays").staticInvoke("toString").arg(_this().ref("value")));
} else {
toString2.body()._return(_this().ref("value").invoke("toString"));
}
}
内容来源于网络,如有侵权,请联系作者删除!