---
title: "EMF校验框架"
author: "winseclone"
date: "2013-01-27T17:58:39Z"
tags: ["Validator", "emf"]
categories: ["编程语言"]
slug: "emf"
draft: false
lastmod: "2013-02-10T02:00:30Z"
id: 1776424
url: "https://winseclone.iteye.com/blog/1776424"
---

EMF提供了两类三种方式来校验EMF模型。

**1&gt;** EMF ECore规则校验

2&gt; Live校验

3&gt; Batch校验

 

## · EMF校验代码

这里用到的代码可以在EMF提供的例子中查看到。**Example-&gt;EMF Validation Framework Plug-ins-&gt;General Validation Example）**

 

## · EMF ECore规则校验

    主要由org.eclipse.emf.ecore.util.EObjectValidator来完成，主要校验EFeature和EAttribute（EXTLibraryPackageImpl.initializePackageContents()）

    或者，通过EOperation/EAnnotation添加操作来实现自定义\[1]的校验。

 

    如果在Ecore中设置的属性，需要有特殊的考虑，可以通过实现自定义的EValidator来代替EMF默认的EObjectValidator。注册方式如下：

```
    // Register package validator
    EValidator.Registry.INSTANCE.put
      (theEcorePackage, 
       new EValidator.Descriptor()
       {
         public EValidator getEValidator()
         {
           return EcoreValidator.INSTANCE;
         }
       });
```

 

可以通过下面两种方式来注册：

1\) 在初始化ModelPackage时实现： org.eclipse.emf.ecore.impl.EcorePackageImpl.init()

2\) 通过StartUp扩展点来实现： org.eclipse.ui.startup \[2]

 

## · Batch模型校验 & Live实时校验 \[3]\[4]

    主要是通过扩展点来注册，实现AbstractModelConstraint(#validate)校验类，并把该类添加到扩展点的constraint节点上：  
![](http://dl.iteye.com/upload/attachment/0079/8994/19feef1c-b138-36dd-bf30-f18819bde9d7.png)

 

需要注意的是，constraintProvider的package的Uri需要和模型中的package-uri对应。如图所示：  
![](http://dl.iteye.com/upload/attachment/0079/8997/d5e8daed-19be-36de-ad56-b88a3f1c2e25.png)  
 

## 参考文章：

\[1] 八进制-模型的验证 [http://www.cnblogs.com/bjzhanghao/archive/2006/08/09/472607.html](http://www.cnblogs.com/bjzhanghao/archive/2006/08/09/472607.html)

官方EMF Validation Overview [http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.emf.doc%2Freferences%2Foverview%2FEMF.Validation.html](http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.emf.doc%2Freferences%2Foverview%2FEMF.Validation.html)

\[2] EMF Validation Adapter [http://help.eclipse.org/galileo/index.jsp?topic=/org.eclipse.emf.validation.doc/tutorials/validationAdapterTutorial.html](http://help.eclipse.org/galileo/index.jsp?topic=%2Forg.eclipse.emf.validation.doc%2Ftutorials%2FvalidationAdapterTutorial.html)

\[3] 使用 EMF Validation 框架来验证 EMF 模型 [http://www.ibm.com/developerworks/cn/opensource/os-cn-ecl-emfvldt/index.html](http://www.ibm.com/developerworks/cn/opensource/os-cn-ecl-emfvldt/index.html)

Validator Service [http://help.eclipse.org/galileo/index.jsp?topic=/org.eclipse.emf.validation.doc/tutorials/validationAdapterTutorial.html](http://help.eclipse.org/galileo/index.jsp?topic=%2Forg.eclipse.emf.validation.doc%2Ftutorials%2FvalidationAdapterTutorial.html)

\[4] Live校验 [http://cutesunshineriver.iteye.com/blog/1186298](http://cutesunshineriver.iteye.com/blog/1186298)