Search code examples
javainterfaceproxy-classes

Making sure an object will implements an interface


I got a class which uses a Proxy. It looks something like this:

public class BarWrapper
{
    private final Bar bar;

    public BarWrapper(Bar bar)
    {
        this.bar = bar;
    }

    public int someMethodInBar()
    {
        return bar.someMethodInBar();
    }

    public int someMethodInBar2()
    {
        return bar.someMethodInBar2();
    }

    public int someMethodInBar3()
    {
        return bar.someMethodInBar3();
    }


    // etc
}

The Bar is some super class and the dynamic type will be a derivative.

I got an interface and I want the wrapper to implement that interface and keep using the proxy with the same methods, but Bar itself doesn't implement that interface and I don't have any access to it. How can I force the user to pass a dynamic type that is not only a derivative of Bar but also implements the interface so I will have no problem doing this:

(Iinterface)bar.interfaceMethod();

Solution

  • If you need the wrapped object to be both a subclass of Bar and an instance of the interface Foo, that Bar doesn't implement, then the only way I see is to accept a subclass of Bar that implements Foo:

    public abstract FooBar extends Bar implements Foo {
    }
    

    That will do what you want: the user will be forced to extend FooBar, and thus to provide a subclass of Bar that implements Foo.