mardi 13 juin 2023

Cast Interface to Subinterface to implement a single method in Java

I would like to "cast" an instance of an interface MyInterface and to a subinterface MyInterfacePlus that only implements the methods in the subinterface.

I can't seem to find an elegant solution. In the example below, MyInterface and OtherInterface are long established and implemented/used extensively by users. I would like to make no changes to MyInterface and add only a default method to OtherInterface. For all existing implementations of OtherInterface, the oneExtraMethod in the result of getMyInterfacePlus will do nothing. That is, the method needs to be there to be called, but it should do nothing.

public interface MyInterface {
    ...//lots of methods
}
public interface MyInterfacePlus extends MyInterface {
    void oneExtraMethod();
}
public interface OtherInterface {
    MyInterface getMyInterface();

    // ANY ELEGANT WAY TO DO THIS?
    default MyInterfacePlus getMyInterfacePlus() {
        MyInterface mi = getMyInterface();
        return new MyInterfacePlus() {
            @Override
            void oneExtraMethod(){};
            // override all (many) methods `methodX` in MyInterface to return `mi.methodX`
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire