Can you force a Java object to implement an interface at runtime?

Now I am next:

1) java interface.

2) A specific java class that does not implement the above interface, but does , contains a method signature corresponding to each of the methods defined in the interface. p>

Since I cannot change the implementation of clause 2, I would like to know whether it is possible to create a method that takes an instance of element 1 as an argument, accepts element 2 without exception of the class.

It seems that various weaving / coercion / AOP mechanisms in Spring should make this possible, but I don't know how to do it.

Is there any way to do this?

+6
java spring
source share
5 answers

Can you force a Java object to inject an interface at runtime?

Yes, using dynamic proxies or rewriting byte code. However, it seems to me that you are looking for an Adapter pattern .

+7
source share

You cannot force the object to implement the interface itself, but you can use something like Proxy to create an object that implements the interface and uses reflection to invoke the corresponding element on the original object.

Of course, if it is only one type of interface and one specific type, you can easily write such a shell without using a proxy:

 public class BarWrapper implements Foo { private final Bar bar; public BarWrapper(Bar bar) { this.bar = bar; } public int someMethodInFoo() { return bar.someMethodInFoo(); } // etc } 
+3
source share

This must be enabled using the adapter. Define another class that implements your interface and delegates the real object:

 class YourAdapter implements YourInterface { private final YourClass realObject; public YourAdapter(YourClass realObject) { this.realObject = realObject; } @Override public methodFromInterface() { // you said the class has the same method signatures although it doesn't // implement the interface, so this should work fine: realObject.methodFromInterface(); } // ....... } 

Now, given the method that expects YourInterface and an object of type YourClass :

 void someMethod(YourInterface param) {} void test() { YourClass object = getFromSomewhere(); someMethod( YourAdapter(object) ); } 
+1
source share

There are basically two ways:

a) write a decorator around your object that implements the interface and delegates your object (this can be done either using a proxy or by writing a simple adapter class)

b) change the byte code. Spring AOP is not efficient enough for this, but the AspectJ compiler. This is single line:

 declare parents: YourClass implements YourInterface; 

Since you do not have access to the source of the class, you will either have to use Load Time Weaving or bind the library jar. All this is well explained in AspectJ in action by Ramnivas Laddad

0
source share

Perhaps you can do what you want with Javassist, either by changing the bytecode of the class, or by creating a wrapper / proxy class.

0
source share

All Articles