Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you force a java object into implementing an interface at runtime?

Tags:

java

spring

Right now I the following:

1) A java interface.

2) A concrete java class that does not implement the aforementioned interface, but does contain a method signature matching every one of the methods defined in the interface.

Since I am unable to change the implementation of item 2, I would like to know if it is possible to make a method that accepts an instance of item 1 as an argument accept item 2 without a class cast exception.

It feels like the various weaving/coercion/AOP mechanics in Spring should make this possible, but I don't know how to do it.

Is there a way to make this happen?

like image 456
dskiles Avatar asked Mar 04 '11 17:03

dskiles


2 Answers

Can you force a java object into implementing an interface at runtime?

Yes, using dynamic proxies or byte-code rewriting. However, to me it seems like you're looking for the Adapter pattern.

like image 64
Johan Sjöberg Avatar answered Oct 19 '22 17:10

Johan Sjöberg


You can't make the object itself implement the interface, but you could use something like Proxy to create an object which implements the interface and uses reflection to call the appropriate member on the original object.

Of course, if it's just the one interface type and the one concrete type, you could easily write such a wrapper without using Proxy:

public class BarWrapper implements Foo
{
    private final Bar bar;

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

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

    // etc
}
like image 44
Jon Skeet Avatar answered Oct 19 '22 17:10

Jon Skeet