代码,因为在这种情况中你的应用程序会使用较少的内存并且提供更快的数据存取(或是使用生成的API或是使用反射API)。尽管生成Java代码满足了大多数应用程序的需要,但是情况并不总是如此。你可能需要处理数据,而不需要使用生成的实现类。例如,你可能不知道在开发时间你将要处理的数据的模型,这就使得生成的Java代码成为一个可怜的选项。
动态的(也就是非生成的)类可以在运行时刻用几种方法来创建。让我们先开始使用Ecore API以编程地方式来创建一个公司模型。公司模型用于描述一个公司,它有一个名称和部门。每个部门由一个数字来唯一标志出并且它还有雇员,每个雇员有一个名称。在下面的代码显示出一个相应于该模型的Ecore元模型。
EcoreFactory ecoreFactory = EcoreFactory.eINSTANCE;
EcorePackage ecorePackage = EcorePackage.eINSTANCE;
//创建一Company类
EClass companyClass = ecoreFactory.createEClass();
companyClass.setName("Company");
//创建公司名
EAttribute companyName = ecoreFactory.createEAttribute();
companyName.setName("name");
companyName.setEType(ecorePackage.getEString());
companyClass.getEStructuralFeatures().add(companyName);
//创建一Employee类
EClass employeeClass = ecoreFactory.createEClass();
employeeClass.setName("Employee");
//在Employee类上添加一个名字属性
EAttribute employeeName = ecoreFactory.createEAttribute();
employeeName.setName("name");
employeeName.setEType(ecorePackage.getEString());
employeeClass.getEStructuralFeatures().add(employeeName);
//创建一Department类
EClass departmentClass = ecoreFactory.createEClass();
departmentClass.setName("Department");
//添加department标志数字
EAttribute departmentNumber = ecoreFactory.createEAttribute();
departmentNumber.setName("number");
departmentNumber.setEType(ecorePackage.getEInt());
departmentClass.getEStructuralFeatures().add(departmentNumber);
//department类能够包含到一个或多个employee的参考
EReference departmentEmployees = ecoreFactory.createEReference();
departmentEmployees.setName("employees");
departmentEmployees.setEType(employeeClass);
//指定它可能是一个或多个employee
departmentEmployees.setUpperBound(ETypedElement.UNBOUNDED_MULTIPLICITY);
departmentEmployees.setContainment(true);
departmentClass.getEStructuralFeatures().add(departmentEmployees);
//company能够包含到一个或多个departments的参考
EReference companyDepartments = ecoreFactory.createEReference();
companyDepartments.setName("department");
companyDepartments.setEType(departmentClass);
companyDepartments.setUpperBound(ETypedElement.UNBOUNDED_MULTIPLICITY);
companyDepartments.setContainment(true);
companyClass.getEStructuralFeatures().add(companyDepartments);
//创建一个包-描述company
EPackage companyPackage = ecoreFactory.createEPackage();
companyPackage.setName("company");
companyPackage.setNsPrefix("company");
companyPackage.setNsURI("http:///com.example.company.ecore");
companyPackage.getEClassifiers().add(employeeClass);
companyPackage.getEClassifiers().add(departmentClass);
companyPackage.getEClassifiers().add(companyClass);
通过使用反射API,你能创建并且
|