從這一講開始,將介紹模板設計的語法,以便大家可以設計自己需要的模板,完成需要的代碼生成。下面主要從兩方面講解語法和服務。
一、語法
Acceleo的變量區是用<%和%>包圍的,當然為了避免某些沖突(例如jsp生成代碼中也包含<%這樣的標記),也可以用另一種標記[%和%]包圍,編譯器會自動識別標記。
1、注釋
Acceleo的注釋用<%--和--%>包圍,可以一行或者多行。
2、metamodel
關鍵字metamodel指定了模板中使用的元模型,它是import區的第一條命令,語法如下:
<%
metamodel MyMetaModelURI
import..
%>
元模型的URI(統一資源標識符)指定了我們將要使用什么樣的元模型,下面是常用元模型的URI:
- UML 1.4 meta model: http://www.obeo.fr/acceleo/uml14
- UML 1.3 meta model: http://www.obeo.fr/uml13
- UML 2.0 meta model: http://www.eclipse.org/uml2/1.0.0/UML or http://www.eclipse.org/uml2/2.0.0/UML
- Ecore meta-model: http://www.eclipse.org/emf/2002/Ecore
應用舉例:
<%
metamodel http://www.obeo.fr/uml14
import fr.obeo.template.commonScript
import fr.obeo.services.StringServices
%>
上面的腳本說明了我們用的元模型是UML1.4。
3、import
和java語言的import類似,acceleo的import命令用在import區,通過import可以鏈接到其它模板或服務文件,然后調用鏈接文件中的腳本或服務。語法如下:
<%
metamodel..
import myPackage.myServicesClass
import myPackage. myScriptTemplate
%>
其中myPackage是文件路徑(例如fr.obeo.acceleo),myServicesClass和myScriptTemplate分別java類的名字和模板的名字。
應用舉例:
<%
metamodel http://www.obeo.fr/uml14
import fr.obeo.template.commonScript
import fr.obeo.services.StringServices
%>
表示本文件的腳本可以調用commonScript.mt中定義的腳本,也可以調用StringServices.class中定義的服務。
4、script
script可以用於標識不同的腳本以及它使用的對象類型,語法如下:
<%script type=”myType” name=”identifier” file=“nameOfGeneratedFile” description=“ myDescription ” post="myPost"%>
myType是腳本將要使用的對象類型,identifier是一個字符串,可以用於標識腳本,nameOfGeneratedFile是生成的代碼文件的相對路徑(包含擴展名),myDescription 描述了腳本的動作,myPost是一個函數,在模板使用完成時調用。
其中的type和name參數是必須有的,其它是可選的。參數對("type","name")標識不同的腳本,對於給定的不同type,腳本(對參數對)必須不同。參數file中可以調用其它腳本。
5、for
acceleo的for語法如下:
<%for (對象列表) {%>
對每個對象的操作
<%}%>
對象列表可以是acceleo的對象integer(“ int ”), Boolean (“boolean”), string (“ String ”), list (“ ENodeList ”),也可以是EMF (“ EObject ”)。
應用舉例:
<%for (eAllContents(“ Class ”)) {%>
The name of the class is: <%name%>.
<%}%>
此腳本表示輸出每個class的名字,關於eAllContents服務將會在后面講解。
6、if
acceleo的if語法如下:
<%if (BooleanExpression) {%>
BooleanExpression為真時執行的命令
<%} else {%>
BooleanExpression為假時執行的命令
<%}%>
BooleanExpression返回的布爾值,其中的操作符可以用== (equal), != (different), < (less than), <= (less or equal than), > (greater than >= (greater than or equal), || (logical or), && (logical and) and ! (negation),其中的操作數可以用腳本、服務或鏈接元模型的值、對象和調用。
應用舉例:
<%if (hasStereotype(“ Entity ”)) {%>
public List myList = new ArrayList();
<%} else {%>
public String myString = “”;
<%}%>
二、總結
本講介紹了acceleo的基本語法,后面將介紹acceleo模板提供的基本服務。