Making sure an object will implements an interface

66 views Asked by At

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();
2

There are 2 answers

0
JB Nizet On BEST ANSWER

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.

2
Dorus On

Instead of taking the object Bar, only accept the interface.

private final Iinterface bar;
public BarWrapper(Iinterface bar)
{
    this.bar = bar;
}

That does require your proxy to only call methods in the interface. It is possible you also want to call methods that are in Bar, but not Iinterface. The only way to enforce that at compile time, is to add these methods to the interface, perhaps extend the interface:

public interface IinterfaceBarWrapper implements Iinterface
{
    public void someMethodInBar();
    public void someMethodInBar2();
    public void someMethodInBar3();
}

...

private final IinterfaceBarWrapper bar;
public BarWrapper(IinterfaceBarWrapper bar)
{
    this.bar = bar;
}