这个东西比较有趣,代码还要区分是否在Eclipse环境下运行。
先看看现象,以EMF例子Library.ecore为例, 测试代码如下:
public class Test {
    
public static void main(String[] args) throws IOException {
        ResourceSet rs 
= new ResourceSetImpl();
        rs.getResourceFactoryRegistry().getExtensionToFactoryMap().put(
                Resource.Factory.Registry.DEFAULT_EXTENSION,
                
new XMIResourceFactoryImpl()); //outside eclipse
        Resource resource 
= rs.createResource(URI
                .createURI(EXTLibraryPackage.eNS_URI));
        
//step a
        Library library = EXTLibraryFactory.eINSTANCE.createLibrary();
        library.setName(
"some lib");
        resource.getContents().add(library);
        
//step b
//        Book book = EXTLibraryFactory.eINSTANCE.createBook();
//        book.setTitle("some book");
//        Employee employee = EXTLibraryFactory.eINSTANCE.createEmployee();
//        employee.setFirstName("some one");
        
//step c
//        library.getBooks().add(book);
//        library.getEmployees().add(employee);
        
//step d
//        resource.getContents().add(book);
    
//        System.out.println(EcoreUtil.getURI(employee));
//        System.out.println(EcoreUtil.getURI(book));
        resource.save(System.out, null);
    }

}


步骤 输出
a ----------------
<?xml version="1.0" encoding="ASCII"?>
<extlib:Library xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:extlib="http:///org/eclipse/emf/examples/library/extlibrary.ecore/1.0.0" name="some lib"/>
#//
#//
<?xml version="1.0" encoding="ASCII"?>
<extlib:Library xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:extlib="http:///org/eclipse/emf/examples/library/extlibrary.ecore/1.0.0" name="some lib"/>
c http:///org/eclipse/emf/examples/library/extlibrary.ecore/1.0.0#//@employees.0
#//
<?xml version="1.0" encoding="ASCII"?>
<extlib:Library xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:extlib="http:///org/eclipse/emf/examples/library/extlibrary.ecore/1.0.0" name="some lib">
  <employees firstName="some one"/>
</extlib:Library>
d http:///org/eclipse/emf/examples/library/extlibrary.ecore/1.0.0#/0/@employees.0
http:///org/eclipse/emf/examples/library/extlibrary.ecore/1.0.0#/1
<?xml version="1.0" encoding="ASCII"?>
<xmi:XMI xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:extlib="http:///org/eclipse/emf/examples/library/extlibrary.ecore/1.0.0">
  <extlib:Library name="some lib">
    <employees firstName="some one"/>
  </extlib:Library>
  <extlib:Book title="some book"/>
</xmi:XMI>

可以看到,没有加入lib的时候,employee/book实例的URI都是#//, employee加入以后有了#//@employees.0, book依旧。
在book加入resource以后有了#/1的URI, employee/book在containment定义分别是true,false,所以employee加入lib以后就随lib加入resource(实例容器)。book则要单独加入。

另外一个有趣的现象是Resource可以容纳多个实例,在step d可以看到输出的根节点由lib变成匿名容器。

如果lib不加入resource又如何呢?
步骤 输出
a ----------------
#//
#//
c #///@employees.0
#//
d ----------------
没加入resource之前,URI是未知的,知道的只是相对父节点的相对segment.