[英]Member variable which must extend class A and implement some interface
I need to have a variable in a class which is an instance of class "ClassA" but which also implements interface "InterfaceI". 我需要在类中有一个变量,它是类“ClassA”的实例,但它也实现了接口“InterfaceI”。
Obviously this can be done for one or the other easily: 显然,这可以很容易地为一个或另一个完成:
private ClassA mVariable;
private InterfaceI mVaraible;
but how can I enforce the object both extends ClassA and implements InterfaceB? 但是如何强制对象既扩展了ClassA又实现了InterfaceB? Something like: 就像是:
private <? extends ClassA & InterfaceI> mVaraible;
is what I need but I have no idea of the syntax or if it is even possible. 是我需要的,但我不知道语法或甚至可能。 I will also need a get and set method, but that can be done with generics (I think?) 我还需要一个get和set方法,但这可以用泛型来完成(我想?)
The obvious solution is 明显的解决方案是
public class ClassB extends ClassA implements InterfaceI{
//whatever here
}
However both InterfaceI and ClassA are part of an external libary, this libary has classes which extend ClassA and InterfaceI and I cant edit them to make them extend ClassB, therefore this solution will not work. 但是,InterfaceI和ClassA都是外部库的一部分,这个库有扩展ClassA和InterfaceI的类,我不能编辑它们以使它们扩展ClassB,因此这个解决方案不起作用。
I have found a rather hacky workaround. 我找到了一个相当hacky的解决方法。
The class contains both a ClassA and InterfaceI reference as follows: 该类包含ClassA和InterfaceI引用,如下所示:
private ClassA mItemClassA;
private InterfaceI mItemInterfaceI;
The set method then looks like this: 然后set方法如下所示:
public void setVaraible(ClassA item){
assert (item instanceof InterfaceI);
mItemClassA = item;
mItemInterfaceI = (InterfaceI) item;
}
Other variations of this could be throwing an exception, returning false, etc if the item is not an instance of InterfaceI 如果该项不是InterfaceI的实例,则其他变体可能是抛出异常,返回false等
Other methods in the class can then call functions from both InterfaceI and ClassA using mItemClassA and mItemInterfaceI. 然后,类中的其他方法可以使用mItemClassA和mItemInterfaceI从InterfaceI和ClassA调用函数。
I am not going to implement a get method for now, but if I did there would likely have to be a version to get the interface and a version to get the class. 我现在不打算实现get方法,但是如果我这样做的话,可能必须有一个版本来获取接口和一个版本来获取类。
You can do this with the generic class types as this: 您可以使用泛型类类型执行此操作,如下所示:
private class ClassB <R extends ClassA & InterfaceI> {
R mVaraible;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.