成员变量,必须扩展类A并实现某些接口 [英] Member variable which must extend class A and implement some interface
问题描述
我需要在一个类中有一个变量,该类是"ClassA"类的实例,但它也实现了"InterfaceI"接口.
I need to have a variable in a class which is an instance of class "ClassA" but which also implements interface "InterfaceI".
显然,这可以轻松地实现:
Obviously this can be done for one or the other easily:
private ClassA mVariable;
private InterfaceI mVaraible;
但是如何强制对象扩展ClassA和实现InterfaceB?像这样:
but how can I enforce the object both extends ClassA and implements InterfaceB? Something like:
private <? extends ClassA & InterfaceI> mVaraible;
是我所需要的,但我不了解语法,甚至不知道是否有可能.我还需要一个get and set方法,但是可以使用泛型(我认为吗?)
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?)
显而易见的解决方案是
public class ClassB extends ClassA implements InterfaceI{
//whatever here
}
尽管InterfaceI和ClassA都是外部库的一部分,但是该库具有扩展ClassA和InterfaceI的类,并且我无法对其进行编辑以使其扩展为ClassB,因此此解决方案将不起作用.
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.
推荐答案
我发现了一个相当棘手的解决方法.
I have found a rather hacky workaround.
该类同时包含ClassA和InterfaceI引用:
The class contains both a ClassA and InterfaceI reference as follows:
private ClassA mItemClassA;
private InterfaceI mItemInterfaceI;
set方法如下:
public void setVaraible(ClassA item){
assert (item instanceof InterfaceI);
mItemClassA = item;
mItemInterfaceI = (InterfaceI) item;
}
如果项不是InterfaceI的实例,则此方法的其他变体可能会引发异常,返回false等.
Other variations of this could be throwing an exception, returning false, etc if the item is not an instance of InterfaceI
然后,该类中的其他方法可以使用mItemClassA和mItemInterfaceI从InterfaceI和ClassA调用函数.
Other methods in the class can then call functions from both InterfaceI and ClassA using mItemClassA and mItemInterfaceI.
我暂时不会实现get方法,但是如果我这样做了,那么可能必须有一个版本才能获取接口和一个版本才能获取类.
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.
这篇关于成员变量,必须扩展类A并实现某些接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!