我正在寻找一种允许在编译时实例之间建立关系的方法。 从抽象的角度来说,这意味着一个接口(interface)的多个子类型与同一类型的多个属性相关,但并非所有子类型都以逻辑方式兼容。我想在编译时检查它。
场景是这样的:
- Animal 实例在构造函数中接收一个国家/地区实例(它所在的国家/地区)。
解决方案:
- 通过 XML 进行运行时检查,例如实例和验证
<Animal> <Type>Lion</Type> <Countries> <Country>Zimbabwe</Country> <Country>Kenya</Country> </Countries> </Animal> <Animal> <Type>Gorilla</Type> <Countries> <Country>Zimbabwe</Country> <Country>Botswana</Country> </Countries> </Animal>
但这只能在运行时失败
- 为每个属性组合创建一个 GorillaCountry、BotswanaCountry 和 KenyaCountry Country 子接口(interface),但如果有 200 个映射,这有点难以维护。
我寻找的是某种模式,以一种良好且可扩展的方式在编译时进行类型检查:
if (animal instanceOf Lion){
if (country instanceOf Botswana) throw new UnsupportedMapping("There are no lions in Botswana")
}
//for Kenya
else if (animal instanceOf Gorilla){
if (country instanceOf Kenya) throw new UnsupportedMapping("There are no gorillas in kenya")
}
对于泛型或映射来说也许是一种棘手的方法......
最佳答案
你想要的是类似 java 8 pluggable type system 的东西.
使用它的示例和框架是 here .
使用它来创建 @Animal 和 @Country 注释似乎完全可能,尽管不一定明智。然后设置相应的类型检查器来查询 appropriate database看看它们是否已经灭绝了。
关于java - 类关系强类型化的最佳模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28780978/