在java中生成和保存EMF模型


package org.eclipse.example.library;

import java.io.IOException;

import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.ETypedElement;
import org.eclipse.emf.ecore.EcoreFactory;
import org.eclipse.emf.ecore.EcorePackage;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.impl.XMLResourceFactoryImpl;

public class EMFTest {

public static void main(String[] args) throws IOException {
EcoreFactory ecoreFactory = EcoreFactory.eINSTANCE;
EClass purchaseOrderClass = ecoreFactory.createEClass();
purchaseOrderClass.setName("PurchaseOrder");
EAttribute shipTo = ecoreFactory.createEAttribute();
shipTo.setName("shipTo");
shipTo.setEType(EcorePackage.Literals.ESTRING);
purchaseOrderClass.getEStructuralFeatures().add(shipTo);
EAttribute billTo = ecoreFactory.createEAttribute();
billTo.setName("billTo");
billTo.setEType(EcorePackage.Literals.ESTRING);
purchaseOrderClass.getEStructuralFeatures().add(billTo);
EClass itemClass = ecoreFactory.createEClass();
itemClass.setName("Item");
EAttribute productName = ecoreFactory.createEAttribute();
productName.setName("productName");
productName.setEType(EcorePackage.Literals.ESTRING);
itemClass.getEStructuralFeatures().add(productName);
EAttribute quantity = ecoreFactory.createEAttribute();
quantity.setName("quantity");
quantity.setEType(EcorePackage.Literals.EINT);
itemClass.getEStructuralFeatures().add(quantity);
EAttribute price = ecoreFactory.createEAttribute();
price.setName("price");
price.setEType(EcorePackage.Literals.EFLOAT);
itemClass.getEStructuralFeatures().add(price);
EReference items = ecoreFactory.createEReference();
items.setName("items");
items.setEType(itemClass);
items.setUpperBound(ETypedElement.UNBOUNDED_MULTIPLICITY);
items.setContainment(true);
purchaseOrderClass.getEStructuralFeatures().add(items);
EPackage poPackage = ecoreFactory.createEPackage();
poPackage.setName("po");
poPackage.setNsPrefix("po");
poPackage.setNsURI("http://www.example.com/SimplePO");
poPackage.getEClassifiers().add(purchaseOrderClass);
poPackage.getEClassifiers().add(itemClass);

ResourceSet metaResourceSet = new ResourceSetImpl();

metaResourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap()
.put("ecore", new XMLResourceFactoryImpl());

Resource metaResource = metaResourceSet.createResource(URI
.createURI("file:///d:/bookStore.ecore"));

metaResource.getContents().add(poPackage);

try {
metaResource.save(null);
} catch (IOException e) {
e.printStackTrace();
}
}

}



参考:
http://www.ibm.com/developerworks/library/os-eclipse-dynamicemf/

你可能感兴趣的:(java)