[英]Force a class to implement one of two interfaces that implements another interface
I am not really sure about Java Annotations, but I think they can solve my problem. 我不太确定Java注释,但是我认为它们可以解决我的问题。
I have an java interface "Target". 我有一个Java接口“ Target”。 This is an empty interface, so I can give that implementation into an "TargetHolder", which is simply a list of Targets.
这是一个空接口,因此我可以将该实现放到“ TargetHolder”中,它只是Target的列表。
Now I only have 2 Types of Targets. 现在我只有2种目标类型。 Type "Alpha" and type "Beta".
键入“ Alpha”,然后键入“ Beta”。
Type "Alpha" has no functionality in common with Type "Beta". 类型“ Alpha”与类型“ Beta”没有共同的功能。
Easiest way would be to just extend "Beta" and "Alpha" from "Target". 最简单的方法是从“ Target”扩展“ Beta”和“ Alpha”。 But with this solution it is possible for a programmer to create a class that extends "Target" only, which must not be possible.
但是使用此解决方案,程序员可以创建仅扩展“ Target”的类,而这是不可能的。
In theory you might be able to implement the checks (at compile time) using an annotation processor. 从理论上讲,您可以使用注释处理器来实现检查(在编译时)。 The problem is that javac will only run an annotation processor on a source file if it finds the right kind annotation in the source.
问题是,javac仅在源文件中找到正确种类的注释时,才会在源文件上运行注释处理器。
"After scanning the source files and classes on the command line to determine what annotations are present, the compiler queries the processors to determine what annotations they process. When a match is found, the processor will be invoked."
“在命令行上扫描源文件和类以确定存在哪些注释后,编译器将查询处理器以确定它们处理的注释。找到匹配项后,将调用处理器。”
(Javac manual) (Javac手册)
But it seems like you want an annotation on an interface to constrain all classes that implement that interface. 但是似乎您想在接口上使用注释来约束实现该接口的所有类。 That means checking all such classes ... but I can't see how you could trigger the running of an annotation processor on a class that has no relevant annotations.
这意味着要检查所有这些类...但是我看不到如何在没有相关注释的类上触发注释处理器的运行。
That leaves you with a couple of options: 这给您提供了两个选择:
My advice would be to put this into the "too hard" basket. 我的建议是将其放入“太硬”的篮子中。 It is probably going to take more time to implement this than you would save in picking up related coding errors earlier.
实现此功能的时间可能要比您早些拾起相关编码错误所节省的时间更多。 (I'm thinking that the case that you are trying to avoid will be picked up when someone tries to use class. So, you (or your client) should find your (their) incorrect class in testing ...)
(我认为,当有人尝试使用类时,您将要避免的情况将会出现。因此,您(或您的客户)应该在测试中找到(他们的)错误的类...)
How about? 怎么样?
Using Tool like JArchitect allows to enforce design rules. 使用JArchitect之类的工具可以强制执行设计规则。 In your case you can use the following cqlinq query:
您可以使用以下cqlinq查询:
warnif count > 0 from t in Types where t.Implement ("Target")
&& (!t.Implement("Alpha")|| !t.Implement("Beta"))
select t
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.