下面列出了怎么用 com.sun.codemodel.internal.JCodeModel 的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Obtains a {@link JType} object for the string representation
* of a type.
*/
public static JType getType( JCodeModel codeModel,
String typeName, ErrorReceiver errorHandler, Locator errorSource ) {
try {
return codeModel.parseType(typeName);
} catch( ClassNotFoundException ee ) {
// make it a warning
errorHandler.warning( new SAXParseException(
Messages.ERR_CLASS_NOT_FOUND.format(typeName)
,errorSource));
// recover by assuming that it's a class that derives from Object
return codeModel.directClass(typeName);
}
}
/**
* Entry point.
*/
public static Model build( XSSchemaSet _schemas, JCodeModel codeModel,
ErrorReceiver _errorReceiver, Options opts ) {
// set up a ring
final Ring old = Ring.begin();
try {
ErrorReceiverFilter ef = new ErrorReceiverFilter(_errorReceiver);
Ring.add(XSSchemaSet.class,_schemas);
Ring.add(codeModel);
Model model = new Model(opts, codeModel, null/*set later*/, opts.classNameAllocator, _schemas);
Ring.add(model);
Ring.add(ErrorReceiver.class,ef);
Ring.add(CodeModelClassFactory.class,new CodeModelClassFactory(ef));
BGMBuilder builder = new BGMBuilder(opts.defaultPackage,opts.defaultPackage2,
opts.isExtensionMode(),opts.getFieldRendererFactory(), opts.activePlugins);
builder._build();
if(ef.hadError()) return null;
else return model;
} finally {
Ring.end(old);
}
}
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() );
}
}
/**
* Obtains a {@link JType} object for the string representation
* of a type.
*/
public static JType getType( JCodeModel codeModel,
String typeName, ErrorReceiver errorHandler, Locator errorSource ) {
try {
return codeModel.parseType(typeName);
} catch( ClassNotFoundException ee ) {
// make it a warning
errorHandler.warning( new SAXParseException(
Messages.ERR_CLASS_NOT_FOUND.format(typeName)
,errorSource));
// recover by assuming that it's a class that derives from Object
return codeModel.directClass(typeName);
}
}
public RELAXNGCompiler(DPattern grammar, JCodeModel codeModel, Options opts) {
this.grammar = grammar;
this.opts = opts;
this.model = new Model(opts,codeModel, NameConverter.smart,opts.classNameAllocator,null);
datatypes.put("",DatatypeLib.BUILTIN);
datatypes.put(WellKnownNamespaces.XML_SCHEMA_DATATYPES,DatatypeLib.XMLSCHEMA);
// find all defines
DefineFinder deff = new DefineFinder();
grammar.accept(deff);
this.defs = deff.defs;
if(opts.defaultPackage2!=null)
pkg = codeModel._package(opts.defaultPackage2);
else
if(opts.defaultPackage!=null)
pkg = codeModel._package(opts.defaultPackage);
else
pkg = codeModel.rootPackage();
}
public RELAXNGCompiler(DPattern grammar, JCodeModel codeModel, Options opts) {
this.grammar = grammar;
this.opts = opts;
this.model = new Model(opts,codeModel, NameConverter.smart,opts.classNameAllocator,null);
datatypes.put("",DatatypeLib.BUILTIN);
datatypes.put(WellKnownNamespaces.XML_SCHEMA_DATATYPES,DatatypeLib.XMLSCHEMA);
// find all defines
DefineFinder deff = new DefineFinder();
grammar.accept(deff);
this.defs = deff.defs;
if(opts.defaultPackage2!=null)
pkg = codeModel._package(opts.defaultPackage2);
else
if(opts.defaultPackage!=null)
pkg = codeModel._package(opts.defaultPackage);
else
pkg = codeModel.rootPackage();
}
public TypeUse getTypeUse(XSSimpleType owner) {
if(typeUse!=null)
return typeUse;
JCodeModel cm = getCodeModel();
JDefinedClass a;
try {
a = cm._class(adapter);
a.hide(); // we assume this is given by the user
a._extends(cm.ref(XmlAdapter.class).narrow(String.class).narrow(
cm.ref(type)));
} catch (JClassAlreadyExistsException e) {
a = e.getExistingClass();
}
// TODO: it's not correct to say that it adapts from String,
// but OTOH I don't think we can compute that.
typeUse = TypeUseFactory.adapt(
CBuiltinLeafInfo.STRING,
new CAdapter(a));
return typeUse;
}
/**
* @param nc
* Usually this should be set in the constructor, but we do allow this parameter
* to be initially null, and then set later.
* @param schemaComponent
* The source schema model, if this is built from XSD.
*/
public Model( Options opts, JCodeModel cm, NameConverter nc, ClassNameAllocator allocator, XSSchemaSet schemaComponent ) {
this.options = opts;
this.codeModel = cm;
this.nameConverter = nc;
this.defaultSymbolSpace = new SymbolSpace(codeModel);
defaultSymbolSpace.setType(codeModel.ref(Object.class));
elementMappings.put(null,new HashMap<QName,CElementInfo>());
if(opts.automaticNameConflictResolution)
allocator = new AutoClassNameAllocator(allocator);
this.allocator = new ClassNameAllocatorWrapper(allocator);
this.schemaComponent = schemaComponent;
this.gloablCustomizations.setParent(this,this);
}
public RELAXNGCompiler(DPattern grammar, JCodeModel codeModel, Options opts) {
this.grammar = grammar;
this.opts = opts;
this.model = new Model(opts,codeModel, NameConverter.smart,opts.classNameAllocator,null);
datatypes.put("",DatatypeLib.BUILTIN);
datatypes.put(WellKnownNamespaces.XML_SCHEMA_DATATYPES,DatatypeLib.XMLSCHEMA);
// find all defines
DefineFinder deff = new DefineFinder();
grammar.accept(deff);
this.defs = deff.defs;
if(opts.defaultPackage2!=null)
pkg = codeModel._package(opts.defaultPackage2);
else
if(opts.defaultPackage!=null)
pkg = codeModel._package(opts.defaultPackage);
else
pkg = codeModel.rootPackage();
}
public CClassInfo(Model model,JCodeModel cm, String fullName, Locator location, QName typeName, QName elementName, XSComponent source, CCustomizations customizations) {
super(model,source,location,customizations);
this.model = model;
int idx = fullName.indexOf('.');
if(idx<0) {
this.parent = model.getPackage(cm.rootPackage());
this.shortName = model.allocator.assignClassName(parent,fullName);
} else {
this.parent = model.getPackage(cm._package(fullName.substring(0,idx)));
this.shortName = model.allocator.assignClassName(parent,fullName.substring(idx+1));
}
this.typeName = typeName;
this.elementName = elementName;
model.add(this);
}
public RELAXNGCompiler(DPattern grammar, JCodeModel codeModel, Options opts) {
this.grammar = grammar;
this.opts = opts;
this.model = new Model(opts,codeModel, NameConverter.smart,opts.classNameAllocator,null);
datatypes.put("",DatatypeLib.BUILTIN);
datatypes.put(WellKnownNamespaces.XML_SCHEMA_DATATYPES,DatatypeLib.XMLSCHEMA);
// find all defines
DefineFinder deff = new DefineFinder();
grammar.accept(deff);
this.defs = deff.defs;
if(opts.defaultPackage2!=null)
pkg = codeModel._package(opts.defaultPackage2);
else
if(opts.defaultPackage!=null)
pkg = codeModel._package(opts.defaultPackage);
else
pkg = codeModel.rootPackage();
}
public TypeUse getTypeUse(XSSimpleType owner) {
if(typeUse!=null)
return typeUse;
JCodeModel cm = getCodeModel();
JDefinedClass a;
try {
a = cm._class(adapter);
a.hide(); // we assume this is given by the user
a._extends(cm.ref(XmlAdapter.class).narrow(String.class).narrow(
cm.ref(type)));
} catch (JClassAlreadyExistsException e) {
a = e.getExistingClass();
}
// TODO: it's not correct to say that it adapts from String,
// but OTOH I don't think we can compute that.
typeUse = TypeUseFactory.adapt(
CBuiltinLeafInfo.STRING,
new CAdapter(a));
return typeUse;
}
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 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 void fromRawValue(JBlock block, String uniqueName, JExpression $var) {
JCodeModel cm = outline().getCodeModel();
JClass elementType = ei.toType(outline(),EXPOSED).boxify();
// [RESULT]
// $t = new ArrayList();
// for( Type e : $var ) {
// $var.add(new JAXBElement(e));
// }
// [core.fromRawValue]
JClass col = cm.ref(ArrayList.class).narrow(elementType);
JVar $t = block.decl(col,uniqueName+"_col",JExpr._new(col));
JForEach loop = block.forEach(itemType(), uniqueName+"_i", $t);
loop.body().invoke($var,"add").arg(createJAXBElement(loop.var()));
acc.fromRawValue(block, uniqueName, $t);
}
public RELAXNGCompiler(DPattern grammar, JCodeModel codeModel, Options opts) {
this.grammar = grammar;
this.opts = opts;
this.model = new Model(opts,codeModel, NameConverter.smart,opts.classNameAllocator,null);
datatypes.put("",DatatypeLib.BUILTIN);
datatypes.put(WellKnownNamespaces.XML_SCHEMA_DATATYPES,DatatypeLib.XMLSCHEMA);
// find all defines
DefineFinder deff = new DefineFinder();
grammar.accept(deff);
this.defs = deff.defs;
if(opts.defaultPackage2!=null)
pkg = codeModel._package(opts.defaultPackage2);
else
if(opts.defaultPackage!=null)
pkg = codeModel._package(opts.defaultPackage);
else
pkg = codeModel.rootPackage();
}
public TypeUse getTypeUse(XSSimpleType owner) {
if(typeUse!=null)
return typeUse;
JCodeModel cm = getCodeModel();
JDefinedClass a;
try {
a = cm._class(adapter);
a.hide(); // we assume this is given by the user
a._extends(cm.ref(XmlAdapter.class).narrow(String.class).narrow(
cm.ref(type)));
} catch (JClassAlreadyExistsException e) {
a = e.getExistingClass();
}
// TODO: it's not correct to say that it adapts from String,
// but OTOH I don't think we can compute that.
typeUse = TypeUseFactory.adapt(
CBuiltinLeafInfo.STRING,
new CAdapter(a));
return typeUse;
}
/**
* Obtains a {@link JType} object for the string representation
* of a type.
*/
public static JType getType( JCodeModel codeModel,
String typeName, ErrorReceiver errorHandler, Locator errorSource ) {
try {
return codeModel.parseType(typeName);
} catch( ClassNotFoundException ee ) {
// make it a warning
errorHandler.warning( new SAXParseException(
Messages.ERR_CLASS_NOT_FOUND.format(typeName)
,errorSource));
// recover by assuming that it's a class that derives from Object
return codeModel.directClass(typeName);
}
}
/**
* Obtains a {@link JType} object for the string representation
* of a type.
*/
public static JType getType( JCodeModel codeModel,
String typeName, ErrorReceiver errorHandler, Locator errorSource ) {
try {
return codeModel.parseType(typeName);
} catch( ClassNotFoundException ee ) {
// make it a warning
errorHandler.warning( new SAXParseException(
Messages.ERR_CLASS_NOT_FOUND.format(typeName)
,errorSource));
// recover by assuming that it's a class that derives from Object
return codeModel.directClass(typeName);
}
}
ElementOutlineImpl(BeanGenerator parent, CElementInfo ei) {
super(ei,
parent.getClassFactory().createClass(
parent.getContainer( ei.parent, Aspect.EXPOSED ), ei.shortName(), ei.getLocator() ));
this.parent = parent;
parent.elements.put(ei,this);
JCodeModel cm = parent.getCodeModel();
implClass._extends(
cm.ref(JAXBElement.class).narrow(
target.getContentInMemoryType().toType(parent,Aspect.EXPOSED).boxify()));
if(ei.hasClass()) {
JType implType = ei.getContentInMemoryType().toType(parent,Aspect.IMPLEMENTATION);
JExpression declaredType = JExpr.cast(cm.ref(Class.class),implType.boxify().dotclass()); // why do we have to cast?
JClass scope=null;
if(ei.getScope()!=null)
scope = parent.getClazz(ei.getScope()).implRef;
JExpression scopeClass = scope==null?JExpr._null():scope.dotclass();
JFieldVar valField = implClass.field(JMod.PROTECTED|JMod.FINAL|JMod.STATIC,QName.class,"NAME",createQName(cm,ei.getElementName()));
// take this opportunity to generate a constructor in the element class
JMethod cons = implClass.constructor(JMod.PUBLIC);
cons.body().invoke("super")
.arg(valField)
.arg(declaredType)
.arg(scopeClass)
.arg(cons.param(implType,"value"));
// generate no-arg constructor in the element class (bug #391; section 5.6.2 in JAXB spec 2.1)
JMethod noArgCons = implClass.constructor(JMod.PUBLIC);
noArgCons.body().invoke("super")
.arg(valField)
.arg(declaredType)
.arg(scopeClass)
.arg(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);
}
/**
* Wraps a type value into a {@link JAXBElement}.
*/
protected final JInvocation createJAXBElement(JExpression $var) {
JCodeModel cm = codeModel();
return JExpr._new(cm.ref(JAXBElement.class))
.arg(JExpr._new(cm.ref(QName.class))
.arg(ei.getElementName().getNamespaceURI())
.arg(ei.getElementName().getLocalPart()))
.arg(getRawType().boxify().erasure().dotclass())
.arg($var);
}
public JavaType getResponseBeanJavaType(){
JCodeModel cm = _responseBean.getJavaType().getType().getType().owner();
if(_asyncOpType.equals(AsyncOperationType.CALLBACK)){
JClass future = cm.ref(java.util.concurrent.Future.class).narrow(cm.ref(Object.class).wildcard());
return new JavaSimpleType(new JAXBTypeAndAnnotation(future));
}else if(_asyncOpType.equals(AsyncOperationType.POLLING)){
JClass polling = cm.ref(javax.xml.ws.Response.class).narrow(_responseBean.getJavaType().getType().getType().boxify());
return new JavaSimpleType(new JAXBTypeAndAnnotation(polling));
}
return null;
}
public JavaType getResponseBeanJavaType(){
JCodeModel cm = _responseBean.getJavaType().getType().getType().owner();
if(_asyncOpType.equals(AsyncOperationType.CALLBACK)){
JClass future = cm.ref(java.util.concurrent.Future.class).narrow(cm.ref(Object.class).wildcard());
return new JavaSimpleType(new JAXBTypeAndAnnotation(future));
}else if(_asyncOpType.equals(AsyncOperationType.POLLING)){
JClass polling = cm.ref(javax.xml.ws.Response.class).narrow(_responseBean.getJavaType().getType().getType().boxify());
return new JavaSimpleType(new JAXBTypeAndAnnotation(polling));
}
return null;
}
public JavaType getResponseBeanJavaType(){
JCodeModel cm = _responseBean.getJavaType().getType().getType().owner();
if(_asyncOpType.equals(AsyncOperationType.CALLBACK)){
JClass future = cm.ref(java.util.concurrent.Future.class).narrow(cm.ref(Object.class).wildcard());
return new JavaSimpleType(new JAXBTypeAndAnnotation(future));
}else if(_asyncOpType.equals(AsyncOperationType.POLLING)){
JClass polling = cm.ref(javax.xml.ws.Response.class).narrow(_responseBean.getJavaType().getType().getType().boxify());
return new JavaSimpleType(new JAXBTypeAndAnnotation(polling));
}
return null;
}
/**
* Wraps a type value into a {@link JAXBElement}.
*/
protected final JInvocation createJAXBElement(JExpression $var) {
JCodeModel cm = codeModel();
return JExpr._new(cm.ref(JAXBElement.class))
.arg(JExpr._new(cm.ref(QName.class))
.arg(ei.getElementName().getNamespaceURI())
.arg(ei.getElementName().getLocalPart()))
.arg(getRawType().boxify().erasure().dotclass())
.arg($var);
}
/**
* Wraps a type value into a {@link JAXBElement}.
*/
protected final JInvocation createJAXBElement(JExpression $var) {
JCodeModel cm = codeModel();
return JExpr._new(cm.ref(JAXBElement.class))
.arg(JExpr._new(cm.ref(QName.class))
.arg(ei.getElementName().getNamespaceURI())
.arg(ei.getElementName().getLocalPart()))
.arg(getRawType().boxify().erasure().dotclass())
.arg($var);
}
public JavaType getResponseBeanJavaType(){
JCodeModel cm = _responseBean.getJavaType().getType().getType().owner();
if(_asyncOpType.equals(AsyncOperationType.CALLBACK)){
JClass future = cm.ref(java.util.concurrent.Future.class).narrow(cm.ref(Object.class).wildcard());
return new JavaSimpleType(new JAXBTypeAndAnnotation(future));
}else if(_asyncOpType.equals(AsyncOperationType.POLLING)){
JClass polling = cm.ref(javax.xml.ws.Response.class).narrow(_responseBean.getJavaType().getType().getType().boxify());
return new JavaSimpleType(new JAXBTypeAndAnnotation(polling));
}
return null;
}
ElementOutlineImpl(BeanGenerator parent, CElementInfo ei) {
super(ei,
parent.getClassFactory().createClass(
parent.getContainer( ei.parent, Aspect.EXPOSED ), ei.shortName(), ei.getLocator() ));
this.parent = parent;
parent.elements.put(ei,this);
JCodeModel cm = parent.getCodeModel();
implClass._extends(
cm.ref(JAXBElement.class).narrow(
target.getContentInMemoryType().toType(parent,Aspect.EXPOSED).boxify()));
if(ei.hasClass()) {
JType implType = ei.getContentInMemoryType().toType(parent,Aspect.IMPLEMENTATION);
JExpression declaredType = JExpr.cast(cm.ref(Class.class),implType.boxify().dotclass()); // why do we have to cast?
JClass scope=null;
if(ei.getScope()!=null)
scope = parent.getClazz(ei.getScope()).implRef;
JExpression scopeClass = scope==null?JExpr._null():scope.dotclass();
JFieldVar valField = implClass.field(JMod.PROTECTED|JMod.FINAL|JMod.STATIC,QName.class,"NAME",createQName(cm,ei.getElementName()));
// take this opportunity to generate a constructor in the element class
JMethod cons = implClass.constructor(JMod.PUBLIC);
cons.body().invoke("super")
.arg(valField)
.arg(declaredType)
.arg(scopeClass)
.arg(cons.param(implType,"value"));
// generate no-arg constructor in the element class (bug #391; section 5.6.2 in JAXB spec 2.1)
JMethod noArgCons = implClass.constructor(JMod.PUBLIC);
noArgCons.body().invoke("super")
.arg(valField)
.arg(declaredType)
.arg(scopeClass)
.arg(JExpr._null());
}
}
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);
}