![](/img/trans.png)
[英]Javadoc only generates the Interface comments and not the class implementations
[英]Restricting the class to accept only any one interface implementations but not mixed?
我有下面的类和接口。
SuperInterface.java
public interface SuperInterface{/*some logic*/}
SubOneInterface.java
public interface SubOneInterface extends SuperInterface{/*some logic*/}
SubTwoInterface.java
public interface SubTwoInterface extends SuperInterface{/*some logic*/}
一个.java
public class One{/*some logic*/}
二.java
public class Two{/*some logic*/}
SubOne.java
public class SubOne extends One implements SubOneInterface{/*some logic*/}
AnotherSubOne.java
public class AnotherSubOne extends One implements SubTwoInterface{/*some logic*/}
SubTwo.java
public class SubTwo extends Two implements SubOneInterface{/*some logic*/}
AnotherSubTwo.java
public class AnotherSubTwo extends Two implements SubTwoInterface{/*some logic*/}
现在,我必须编写一个类,其中将包含SubOneInterface和SubTwoInterface的实现类。
public class ClassesHolder{
private List<One> one;
private List<Two> two;
//setters and getters
}
现在, ClassesHolder
应该接受实现SubOneInterface
或SubTwoInterface
所有对象( One和Two的子类 ),但不能同时使用这两个接口。
如果他们尝试使用混合接口实现填充列表,则应引发异常。
我怎样才能做到这一点?
您不能轻易排除实现特定接口的类。 如果您的合同要求引用SubOneInterface
,那么它将接受实现SubOneInterface
类,无论它们实现了什么。
否则尝试似乎是一个错误的设计。 如果您的ClassesHolder
包含一个实现SubOneInterface
的类,则它将通过该类引用该类,并且由于未引用其他接口,因此将隐藏任何其他功能。
您可以在加入名单后检查您的课程,例如
public void addToListOfOnes(final SubOneInterface obj) {
if (obj instanceof SubTwoInterface) {
// throw an exception
}
}
但这似乎很差/违反直觉。 我将退后一步,再次查看您的设计。
看下面我的例子。 如果您可以引入其他接口作为接口的基本类型,则此解决方案应适用于您。 一旦实例化,它将不是One
子类型或Two
子类型。
public class Example {
public static void main(String[] args) throws Exception {
ClassesHolder<One> ones = new ClassesHolder<One>();
ones.add(new SubOne());
ones.add(new SubSubOne());
}
}
interface Zero {}
interface One extends Zero {};
interface Two extends Zero {};
class SubOne implements One {};
class SubSubOne implements One {};
class SubTwo implements Two {};
class SubSubTwo implements Two {};
class ClassesHolder<V extends Zero> {
public <T extends V> void add(T item) {}
}
使用Class.isInterface() ,可以检查它是否属于特定接口。 根据您的要求,要在添加到列表之前进行检查,然后尝试检查类是SubOneInterface还是SubTwoInterface的接口,但不能同时使用这两个接口。
那有意义吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.