下面列出了怎么用 com.sun.codemodel.internal.JExpr 的API类实例代码及写法,或者点击链接到github查看源代码。
private void generate( ClassOutlineImpl outline, CPropertyInfo prop ) {
// add isSetXXX and unsetXXX.
MethodWriter writer = outline.createMethodWriter();
JCodeModel codeModel = outline.parent().getCodeModel();
FieldAccessor acc = core.create(JExpr._this());
if( generateIsSetMethod ) {
// [RESULT] boolean isSetXXX()
JExpression hasSetValue = acc.hasSetValue();
if( hasSetValue==null ) {
// this field renderer doesn't support the isSet/unset methods generation.
// issue an error
throw new UnsupportedOperationException();
}
writer.declareMethod(codeModel.BOOLEAN,"isSet"+this.prop.getName(true))
.body()._return( hasSetValue );
}
if( generateUnSetMethod ) {
// [RESULT] void unsetXXX()
acc.unsetValues(
writer.declareMethod(codeModel.VOID,"unset"+this.prop.getName(true)).body() );
}
}
private void writeMember(JDefinedClass cls, TypeMirror paramType,
String paramName) {
if (cls == null)
return;
String accessorName =BindingHelper.mangleNameToPropertyName(paramName);
String getterPrefix = paramType.toString().equals("boolean")? "is" : "get";
JType propType = getType(paramType);
JMethod m = cls.method(JMod.PUBLIC, propType, getterPrefix+ accessorName);
JDocComment methodDoc = m.javadoc();
JCommentPart ret = methodDoc.addReturn();
ret.add("returns "+propType.name());
JBlock body = m.body();
body._return( JExpr._this().ref(paramName) );
m = cls.method(JMod.PUBLIC, cm.VOID, "set"+accessorName);
JVar param = m.param(propType, paramName);
methodDoc = m.javadoc();
JCommentPart part = methodDoc.addParam(paramName);
part.add("the value for the "+ paramName+" property");
body = m.body();
body.assign( JExpr._this().ref(paramName), param );
}
public void toRawValue(JBlock block, JVar $var) {
JCodeModel cm = outline().getCodeModel();
JClass elementType = ei.toType(outline(),EXPOSED).boxify();
// [RESULT]
// $var = new ArrayList();
// for( JAXBElement e : [core.toRawValue] ) {
// if(e==null)
// $var.add(null);
// else
// $var.add(e.getValue());
// }
block.assign($var,JExpr._new(cm.ref(ArrayList.class).narrow(itemType().boxify())));
JVar $col = block.decl(core.getRawType(), "col" + hashCode());
acc.toRawValue(block,$col);
JForEach loop = block.forEach(elementType, "v" + hashCode()/*unique string handling*/, $col);
JConditional cond = loop.body()._if(loop.var().eq(JExpr._null()));
cond._then().invoke($var,"add").arg(JExpr._null());
cond._else().invoke($var,"add").arg(loop.var().invoke("getValue"));
}
private void generate( ClassOutlineImpl outline, CPropertyInfo prop ) {
// add isSetXXX and unsetXXX.
MethodWriter writer = outline.createMethodWriter();
JCodeModel codeModel = outline.parent().getCodeModel();
FieldAccessor acc = core.create(JExpr._this());
if( generateIsSetMethod ) {
// [RESULT] boolean isSetXXX()
JExpression hasSetValue = acc.hasSetValue();
if( hasSetValue==null ) {
// this field renderer doesn't support the isSet/unset methods generation.
// issue an error
throw new UnsupportedOperationException();
}
writer.declareMethod(codeModel.BOOLEAN,"isSet"+this.prop.getName(true))
.body()._return( hasSetValue );
}
if( generateUnSetMethod ) {
// [RESULT] void unsetXXX()
acc.unsetValues(
writer.declareMethod(codeModel.VOID,"unset"+this.prop.getName(true)).body() );
}
}
public JExpression createConstant(Outline outline, XmlString lexical) {
if(isCollection()) return null;
if(adapter==null) return coreType.createConstant(outline, lexical);
// [RESULT] new Adapter().unmarshal(CONSTANT);
JExpression cons = coreType.createConstant(outline, lexical);
Class<? extends XmlAdapter> atype = adapter.getAdapterIfKnown();
// try to run the adapter now rather than later.
if(cons instanceof JStringLiteral && atype!=null) {
JStringLiteral scons = (JStringLiteral) cons;
XmlAdapter a = ClassFactory.create(atype);
try {
Object value = a.unmarshal(scons.str);
if(value instanceof String) {
return JExpr.lit((String)value);
}
} catch (Exception e) {
// assume that we can't eagerly bind this
}
}
return JExpr._new(adapter.getAdapterClass(outline)).invoke("unmarshal").arg(cons);
}
private void writeMember(JDefinedClass cls, TypeMirror paramType,
String paramName) {
if (cls == null)
return;
String accessorName =BindingHelper.mangleNameToPropertyName(paramName);
String getterPrefix = paramType.toString().equals("boolean")? "is" : "get";
JType propType = getType(paramType);
JMethod m = cls.method(JMod.PUBLIC, propType, getterPrefix+ accessorName);
JDocComment methodDoc = m.javadoc();
JCommentPart ret = methodDoc.addReturn();
ret.add("returns "+propType.name());
JBlock body = m.body();
body._return( JExpr._this().ref(paramName) );
m = cls.method(JMod.PUBLIC, cm.VOID, "set"+accessorName);
JVar param = m.param(propType, paramName);
methodDoc = m.javadoc();
JCommentPart part = methodDoc.addParam(paramName);
part.add("the value for the "+ paramName+" property");
body = m.body();
body.assign( JExpr._this().ref(paramName), param );
}
private void writeMember(JDefinedClass cls, TypeMirror paramType,
String paramName) {
if (cls == null)
return;
String accessorName =BindingHelper.mangleNameToPropertyName(paramName);
String getterPrefix = paramType.toString().equals("boolean")? "is" : "get";
JType propType = getType(paramType);
JMethod m = cls.method(JMod.PUBLIC, propType, getterPrefix+ accessorName);
JDocComment methodDoc = m.javadoc();
JCommentPart ret = methodDoc.addReturn();
ret.add("returns "+propType.name());
JBlock body = m.body();
body._return( JExpr._this().ref(paramName) );
m = cls.method(JMod.PUBLIC, cm.VOID, "set"+accessorName);
JVar param = m.param(propType, paramName);
methodDoc = m.javadoc();
JCommentPart part = methodDoc.addParam(paramName);
part.add("the value for the "+ paramName+" property");
body = m.body();
body.assign( JExpr._this().ref(paramName), param );
}
private void writeMember(JDefinedClass cls, TypeMirror paramType,
String paramName) {
if (cls == null)
return;
String accessorName =BindingHelper.mangleNameToPropertyName(paramName);
String getterPrefix = paramType.toString().equals("boolean")? "is" : "get";
JType propType = getType(paramType);
JMethod m = cls.method(JMod.PUBLIC, propType, getterPrefix+ accessorName);
JDocComment methodDoc = m.javadoc();
JCommentPart ret = methodDoc.addReturn();
ret.add("returns "+propType.name());
JBlock body = m.body();
body._return( JExpr._this().ref(paramName) );
m = cls.method(JMod.PUBLIC, cm.VOID, "set"+accessorName);
JVar param = m.param(propType, paramName);
methodDoc = m.javadoc();
JCommentPart part = methodDoc.addParam(paramName);
part.add("the value for the "+ paramName+" property");
body = m.body();
body.assign( JExpr._this().ref(paramName), param );
}
@Override
public void generateAccessors() {
final MethodWriter writer = outline.createMethodWriter();
final Accessor acc = create(JExpr._this());
// [RESULT]
// List getXXX() {
// return <ref>;
// }
$get = writer.declareMethod(listT,"get"+prop.getName(true));
writer.javadoc().append(prop.javadoc);
JBlock block = $get.body();
fixNullRef(block); // avoid using an internal getter
block._return(acc.ref(true));
String pname = NameConverter.standard.toVariableName(prop.getName(true));
writer.javadoc().append(
"Gets the value of the "+pname+" property.\n\n"+
"<p>\n" +
"This accessor method returns a reference to the live list,\n" +
"not a snapshot. Therefore any modification you make to the\n" +
"returned list will be present inside the JAXB object.\n" +
"This is why there is not a <CODE>set</CODE> method for the " +pname+ " property.\n" +
"\n"+
"<p>\n" +
"For example, to add a new item, do as follows:\n"+
"<pre>\n"+
" get"+prop.getName(true)+"().add(newItem);\n"+
"</pre>\n"+
"\n\n"
);
writer.javadoc().append(
"<p>\n" +
"Objects of the following type(s) are allowed in the list\n")
.append(listPossibleTypes(prop));
}
public JExpression generate( JCodeModel codeModel, JExpression literal ) {
// WhitespaceProcessor.replace(<literal>);
if( literal instanceof JStringLiteral )
// optimize
return JExpr.lit( WhiteSpaceProcessor.replace(((JStringLiteral)literal).str) );
else
return codeModel.ref(WhiteSpaceProcessor.class)
.staticInvoke("replace").arg(literal);
}
/**
* Case from {@link #exposedType} to {@link #implType} if necessary.
*/
protected final JExpression castToImplType( JExpression exp ) {
if(implType==exposedType)
return exp;
else
return JExpr.cast(implType,exp);
}
private void writeClassLoaderResourceWSDLLocation(String className, JDefinedClass cls, JFieldVar urlField, JFieldVar exField) {
JBlock staticBlock = cls.init();
staticBlock.assign(urlField, JExpr.dotclass(cm.ref(className)).invoke("getClassLoader").invoke("getResource").arg(wsdlLocation));
JVar exVar = staticBlock.decl(cm.ref(WebServiceException.class), "e", JExpr._null());
JConditional ifBlock = staticBlock._if(urlField.eq(JExpr._null()));
ifBlock._then().assign(exVar, JExpr._new(cm.ref(WebServiceException.class)).arg(
"Cannot find "+JExpr.quotify('\'', wsdlLocation)+" wsdl. Place the resource correctly in the classpath."));
staticBlock.assign(exField, exVar);
}
public void toRawValue(JBlock block, JVar $var) {
// [RESULT]
// if([core.hasSetValue])
// $var = [core.toRawValue].getValue();
// else
// $var = null;
JConditional cond = block._if(acc.hasSetValue());
JVar $v = cond._then().decl(core.getRawType(), "v" + hashCode());// TODO: unique value control
acc.toRawValue(cond._then(),$v);
cond._then().assign($var,$v.invoke("getValue"));
cond._else().assign($var, JExpr._null());
}
public void toRawValue(JBlock block, JVar $var) {
// [RESULT]
// if([core.hasSetValue])
// $var = [core.toRawValue].getValue();
// else
// $var = null;
JConditional cond = block._if(acc.hasSetValue());
JVar $v = cond._then().decl(core.getRawType(), "v" + hashCode());// TODO: unique value control
acc.toRawValue(cond._then(),$v);
cond._then().assign($var,$v.invoke("getValue"));
cond._else().assign($var, JExpr._null());
}
/**
* Case from {@link #exposedType} to {@link #implType} if necessary.
*/
protected final JExpression castToImplType( JExpression exp ) {
if(implType==exposedType)
return exp;
else
return JExpr.cast(implType,exp);
}
public JExpression createConstant(Outline outline, XmlString lexical) {
QName qn = DatatypeConverter.parseQName(lexical.value,new NamespaceContextAdapter(lexical));
return JExpr._new(outline.getCodeModel().ref(QName.class))
.arg(qn.getNamespaceURI())
.arg(qn.getLocalPart())
.arg(qn.getPrefix());
}
public JExpression generate( JCodeModel codeModel, JExpression literal ) {
// WhitespaceProcessor.replace(<literal>);
if( literal instanceof JStringLiteral )
// optimize
return JExpr.lit( WhiteSpaceProcessor.collapse(((JStringLiteral)literal).str) );
else
return codeModel.ref(WhiteSpaceProcessor.class)
.staticInvoke("collapse").arg(literal);
}
public void toRawValue(JBlock block, JVar $var) {
// [RESULT]
// if([core.hasSetValue])
// $var = [core.toRawValue].getValue();
// else
// $var = null;
JConditional cond = block._if(acc.hasSetValue());
JVar $v = cond._then().decl(core.getRawType(), "v" + hashCode());// TODO: unique value control
acc.toRawValue(cond._then(),$v);
cond._then().assign($var,$v.invoke("getValue"));
cond._else().assign($var, JExpr._null());
}
public JExpression generate( JCodeModel codeModel, JExpression literal ) {
// WhitespaceProcessor.replace(<literal>);
if( literal instanceof JStringLiteral )
// optimize
return JExpr.lit( WhiteSpaceProcessor.collapse(((JStringLiteral)literal).str) );
else
return codeModel.ref(WhiteSpaceProcessor.class)
.staticInvoke("collapse").arg(literal);
}
@Override
public void generateAccessors() {
final MethodWriter writer = outline.createMethodWriter();
final Accessor acc = create(JExpr._this());
// [RESULT]
// List getXXX() {
// return <ref>;
// }
$get = writer.declareMethod(listT,"get"+prop.getName(true));
writer.javadoc().append(prop.javadoc);
JBlock block = $get.body();
fixNullRef(block); // avoid using an internal getter
block._return(acc.ref(true));
String pname = NameConverter.standard.toVariableName(prop.getName(true));
writer.javadoc().append(
"Gets the value of the "+pname+" property.\n\n"+
"<p>\n" +
"This accessor method returns a reference to the live list,\n" +
"not a snapshot. Therefore any modification you make to the\n" +
"returned list will be present inside the JAXB object.\n" +
"This is why there is not a <CODE>set</CODE> method for the " +pname+ " property.\n" +
"\n"+
"<p>\n" +
"For example, to add a new item, do as follows:\n"+
"<pre>\n"+
" get"+prop.getName(true)+"().add(newItem);\n"+
"</pre>\n"+
"\n\n"
);
writer.javadoc().append(
"<p>\n" +
"Objects of the following type(s) are allowed in the list\n")
.append(listPossibleTypes(prop));
}
DualObjectFactoryGenerator(BeanGenerator outline, Model model, JPackage targetPackage) {
this.publicOFG = new PublicObjectFactoryGenerator(outline,model,targetPackage);
this.privateOFG = new PrivateObjectFactoryGenerator(outline,model,targetPackage);
// put the marker so that we can detect missing jaxb.properties
publicOFG.getObjectFactory().field(JMod.PRIVATE|JMod.STATIC|JMod.FINAL,
Void.class, "_useJAXBProperties", JExpr._null());
}
public void toRawValue(JBlock block, JVar $var) {
// [RESULT]
// if([core.hasSetValue])
// $var = [core.toRawValue].getValue();
// else
// $var = null;
JConditional cond = block._if(acc.hasSetValue());
JVar $v = cond._then().decl(core.getRawType(), "v" + hashCode());// TODO: unique value control
acc.toRawValue(cond._then(),$v);
cond._then().assign($var,$v.invoke("getValue"));
cond._else().assign($var, JExpr._null());
}
private void writeAbsWSDLLocation(JDefinedClass cls, JFieldVar urlField, JFieldVar exField) {
JBlock staticBlock = cls.init();
JVar urlVar = staticBlock.decl(cm.ref(URL.class), "url", JExpr._null());
JVar exVar = staticBlock.decl(cm.ref(WebServiceException.class), "e", JExpr._null());
JTryBlock tryBlock = staticBlock._try();
tryBlock.body().assign(urlVar, JExpr._new(cm.ref(URL.class)).arg(wsdlLocation));
JCatchBlock catchBlock = tryBlock._catch(cm.ref(MalformedURLException.class));
catchBlock.param("ex");
catchBlock.body().assign(exVar, JExpr._new(cm.ref(WebServiceException.class)).arg(JExpr.ref("ex")));
staticBlock.assign(urlField, urlVar);
staticBlock.assign(exField, exVar);
}
@Override
public void generateAccessors() {
final MethodWriter writer = outline.createMethodWriter();
final Accessor acc = create(JExpr._this());
// [RESULT]
// List getXXX() {
// return <ref>;
// }
$get = writer.declareMethod(listT,"get"+prop.getName(true));
writer.javadoc().append(prop.javadoc);
JBlock block = $get.body();
fixNullRef(block); // avoid using an internal getter
block._return(acc.ref(true));
String pname = NameConverter.standard.toVariableName(prop.getName(true));
writer.javadoc().append(
"Gets the value of the "+pname+" property.\n\n"+
"<p>\n" +
"This accessor method returns a reference to the live list,\n" +
"not a snapshot. Therefore any modification you make to the\n" +
"returned list will be present inside the JAXB object.\n" +
"This is why there is not a <CODE>set</CODE> method for the " +pname+ " property.\n" +
"\n"+
"<p>\n" +
"For example, to add a new item, do as follows:\n"+
"<pre>\n"+
" get"+prop.getName(true)+"().add(newItem);\n"+
"</pre>\n"+
"\n\n"
);
writer.javadoc().append(
"<p>\n" +
"Objects of the following type(s) are allowed in the list\n")
.append(listPossibleTypes(prop));
}
/**
* Generates an attribute wildcard property on a class.
*/
private void generateAttributeWildcard(ClassOutlineImpl cc) {
String FIELD_NAME = "otherAttributes";
String METHOD_SEED = model.getNameConverter().toClassName(FIELD_NAME);
JClass mapType = codeModel.ref(Map.class).narrow(QName.class, String.class);
JClass mapImpl = codeModel.ref(HashMap.class).narrow(QName.class, String.class);
// [RESULT]
// Map<QName,String> m = new HashMap<QName,String>();
JFieldVar $ref = cc.implClass.field(JMod.PRIVATE,
mapType, FIELD_NAME, JExpr._new(mapImpl));
$ref.annotate2(XmlAnyAttributeWriter.class);
MethodWriter writer = cc.createMethodWriter();
JMethod $get = writer.declareMethod(mapType, "get" + METHOD_SEED);
$get.javadoc().append(
"Gets a map that contains attributes that aren't bound to any typed property on this class.\n\n"
+ "<p>\n"
+ "the map is keyed by the name of the attribute and \n"
+ "the value is the string value of the attribute.\n"
+ "\n"
+ "the map returned by this method is live, and you can add new attribute\n"
+ "by updating the map directly. Because of this design, there's no setter.\n");
$get.javadoc().addReturn().append("always non-null");
$get.body()._return($ref);
}
private void writeAbsWSDLLocation(JDefinedClass cls, JFieldVar urlField, JFieldVar exField) {
JBlock staticBlock = cls.init();
JVar urlVar = staticBlock.decl(cm.ref(URL.class), "url", JExpr._null());
JVar exVar = staticBlock.decl(cm.ref(WebServiceException.class), "e", JExpr._null());
JTryBlock tryBlock = staticBlock._try();
tryBlock.body().assign(urlVar, JExpr._new(cm.ref(URL.class)).arg(wsdlLocation));
JCatchBlock catchBlock = tryBlock._catch(cm.ref(MalformedURLException.class));
catchBlock.param("ex");
catchBlock.body().assign(exVar, JExpr._new(cm.ref(WebServiceException.class)).arg(JExpr.ref("ex")));
staticBlock.assign(urlField, urlVar);
staticBlock.assign(exField, exVar);
}
private void writeClassLoaderResourceWSDLLocation(String className, JDefinedClass cls, JFieldVar urlField, JFieldVar exField) {
JBlock staticBlock = cls.init();
staticBlock.assign(urlField, JExpr.dotclass(cm.ref(className)).invoke("getClassLoader").invoke("getResource").arg(wsdlLocation));
JVar exVar = staticBlock.decl(cm.ref(WebServiceException.class), "e", JExpr._null());
JConditional ifBlock = staticBlock._if(urlField.eq(JExpr._null()));
ifBlock._then().assign(exVar, JExpr._new(cm.ref(WebServiceException.class)).arg(
"Cannot find "+JExpr.quotify('\'', wsdlLocation)+" wsdl. Place the resource correctly in the classpath."));
staticBlock.assign(exField, exVar);
}
private void writeClassLoaderBaseResourceWSDLLocation(String className, JDefinedClass cls, JFieldVar urlField, JFieldVar exField) {
JBlock staticBlock = cls.init();
JVar exVar = staticBlock.decl(cm.ref(WebServiceException.class), "e", JExpr._null());
JVar urlVar = staticBlock.decl(cm.ref(URL.class), "url", JExpr._null());
JTryBlock tryBlock = staticBlock._try();
tryBlock.body().assign(urlVar, JExpr._new(cm.ref(URL.class)).arg(JExpr.dotclass(cm.ref(className)).invoke("getResource").arg(".")).arg(wsdlLocation));
JCatchBlock catchBlock = tryBlock._catch(cm.ref(MalformedURLException.class));
JVar murlVar = catchBlock.param("murl");
catchBlock.body().assign(exVar, JExpr._new(cm.ref(WebServiceException.class)).arg(murlVar));
staticBlock.assign(urlField, urlVar);
staticBlock.assign(exField, exVar);
}
@Override
public void generateAccessors() {
final MethodWriter writer = outline.createMethodWriter();
final Accessor acc = create(JExpr._this());
// [RESULT]
// List getXXX() {
// return <ref>;
// }
$get = writer.declareMethod(listT,"get"+prop.getName(true));
writer.javadoc().append(prop.javadoc);
JBlock block = $get.body();
fixNullRef(block); // avoid using an internal getter
block._return(acc.ref(true));
String pname = NameConverter.standard.toVariableName(prop.getName(true));
writer.javadoc().append(
"Gets the value of the "+pname+" property.\n\n"+
"<p>\n" +
"This accessor method returns a reference to the live list,\n" +
"not a snapshot. Therefore any modification you make to the\n" +
"returned list will be present inside the JAXB object.\n" +
"This is why there is not a <CODE>set</CODE> method for the " +pname+ " property.\n" +
"\n"+
"<p>\n" +
"For example, to add a new item, do as follows:\n"+
"<pre>\n"+
" get"+prop.getName(true)+"().add(newItem);\n"+
"</pre>\n"+
"\n\n"
);
writer.javadoc().append(
"<p>\n" +
"Objects of the following type(s) are allowed in the list\n")
.append(listPossibleTypes(prop));
}
public void toRawValue(JBlock block, JVar $var) {
// [RESULT]
// $<var>.addAll(bean.getLIST());
// list.toArray( array );
block.assign($var,JExpr._new(codeModel.ref(ArrayList.class).narrow(exposedType.boxify())).arg(
$target.invoke($get)
));
}