Member variable which must extend class A and impl

2019-06-22 08:46发布

问题:

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;
}