Member variable which must extend class A and implement some interface

匆匆过客 提交于 2019-12-10 15:33:09

问题


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;

but how can I enforce the object both extends ClassA and implements 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?)

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.


回答1:


I have found a rather hacky workaround.

The class contains both a ClassA and InterfaceI reference as follows:

private ClassA mItemClassA;
private InterfaceI mItemInterfaceI;

The set method then looks like this:

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

Other methods in the class can then call functions from both InterfaceI and ClassA using mItemClassA and mItemInterfaceI.

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.




回答2:


You can do this with the generic class types as this:

private class ClassB <R extends ClassA & InterfaceI> {
    R mVaraible;
}


来源:https://stackoverflow.com/questions/20582721/member-variable-which-must-extend-class-a-and-implement-some-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!