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?
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
.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With