Franz Kafka
Franz Kafka

Reputation: 10831

Java forcing interface on 3rd party class through anonymous class

I've got some 3rd party beans that have method signatures that fit quite well onto an existing interface but it does not implement the interface.

Now I would like to do something like this, which doesn't work. Is there some workaround?

 someBean.setSomeInterface(
         new Interface() extends SomeBeanThatMatchesAlotOfMethodsOfTheInterface {
     });

Upvotes: 2

Views: 852

Answers (2)

Cratylus
Cratylus

Reputation: 54074

You can use a decorator pattern for this

Define a class that implements your interface and in all the method calls delegate to the someBean implementation.

Upvotes: 2

Chris Aldrich
Chris Aldrich

Reputation: 1922

I think about all you could do is extend their class (like you did above) and then say implements.

Eg.

public class MyImplementingClass extends SomeBeanThatMatchesAlotOfMethodsOfTheInterface implements MyInterface {

....
}

Of course by basing their code on your interface it is possible that it could break in the future. Just be aware of that.

Upvotes: 2

Related Questions