模型约束验证
给定一个基于通用树(Java)的数据模型。假设
abstract class XModel {
long id;
XModel parent;
}
class ProjectModel extends XModel {
String customer;
}
class FileModel extends XModel {
String name;
}
class FolderModel extends XModel {
String name;
String attributes;
}
我的挑战是确保 FileModel 只在 FolderModels(或 ProjectModels)中使用,FolderModels 只在 ProjectModels 中使用。 由于模型应该是可扩展的 - 是否有任何通用方法可以执行此约束验证(如 XML 模式),而无需在验证方法中对父子关系进行硬编码?
Given a generic tree based (Java) data model. Let's say
abstract class XModel {
long id;
XModel parent;
}
class ProjectModel extends XModel {
String customer;
}
class FileModel extends XModel {
String name;
}
class FolderModel extends XModel {
String name;
String attributes;
}
My challenge is to make sure that FileModels are only used in FolderModels (or PrjectModels) and FolderModels are only used in ProjectModels.
Since the model should be extensible - is there any generic way to do this constraint validation (like XML Schema does) without hardcoding the parent-child-realtions in a validation method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不确定它有多大用处 - 取决于您如何创建树,但这可能有效:
更新
要将验证逻辑与模型本身分开,您可以使用一些运行时验证器,例如 Hibernate 或 Spring 验证器。
I'm not sure how useful it would be - depends on how you create the tree, but this might work:
UPDATE
To separate validation logic from model itself you could use some runtime validators like Hibernate or Spring validators.
我将使用描述限制的泛型和接口
这样,子级仅将父级限制为接口而不是具体类型
I would use generics and interfaces that describe the restrictions
This way the child only restricts the parent to an interface not a concrete type
如果您不想将这些约束放入代码中,则必须自己编写一个由某些外部数据提供的验证方法。据我所知,除了使用泛型之外,没有这样的内置选项(在编译器中),这需要您在代码中表达约束。
If you don't want to put those constraints into code, you'd have to write a validation method that is fed by some external data yourself. AFAIK there's no such built in option (in the compiler) besides using Generics, which would require you to express the constraints in code.