如何获取接口FloatingPoint名称而非其父接口DataTypeA?
解决EReference获取子接口名称的问题
嘿,这个问题我熟!你遇到的情况是因为EReference的EType指向的是声明该引用时的类型(也就是DataTypeA),而不是你实际使用的子接口FloatingPoint。哪怕子接口继承了这个引用,它的类型不会自动替换成子接口的类型,所以直接打印EType的名称只会得到父接口的名字。
下面给你两种针对性的解决方案,你可以根据自己的实际场景选择:
方案一:基于当前EClass(如果MetaObject是FloatingPoint的EClass实例)
如果你的MetaObject本身就是FloatingPoint对应的EClass对象,那可以通过检查当前类是否是父接口的子类型,来替换成子接口的名称:
// 先确保MetaObject是FloatingPoint对应的EClass EClass currentClass = (EClass) MetaObject; for (int i = 0, size = currentClass.getEAllReferences().size(); i < size; ++i) { EReference reference = currentClass.getEAllReferences().get(i); if (reference.isContainment()){ if (reference.getEType() instanceof EClass) { EClass containedClass = (EClass) reference.getEType(); String className; // 判断当前类是否是该引用类型的子类型 if (containedClass.isSuperTypeOf(currentClass)) { className = currentClass.getName(); // 用子接口名称 } else { className = containedClass.getName(); // 用原声明类型名称 } System.out.println(className); } } }
方案二:查找指定子类型(如果需要动态获取所有可能的子接口)
如果你不确定当前使用的子类型,或者需要遍历所有继承自DataTypeA的子接口,可以通过getEAllSubtypes()方法获取所有子类型,再筛选出你需要的FloatingPoint:
for (int i = 0, size = MetaObject.getEAllReferences().size(); i < size; ++i) { EReference reference = MetaObject.getEAllReferences().get(i); if (reference.isContainment()){ if (reference.getEType() instanceof EClass) { EClass containedClass = (EClass) reference.getEType(); // 遍历所有子类型,找到FloatingPoint for (EClass subType : containedClass.getEAllSubtypes()) { if ("FloatingPoint".equals(subType.getName())) { System.out.println(subType.getName()); break; } } // 如果没有找到目标子类型,可以选择输出原类型 // System.out.println(containedClass.getName()); } } }
核心思路就是:你需要区分声明类型和实际使用的子类型,通过当前上下文(比如当前的EClass或者实例)来关联到你想要的子接口名称。
内容的提问来源于stack exchange,提问作者George
相关产品推荐
相关产品推荐

