What's the de-facto solution for building dynamic implementation of interfaces and/or abstract classes? What I basically want is:
interface IMyEntity {
int getValue1();
void setValue1(int x);
}
...
class MyEntityDispatcher implements WhateverDispatcher {
public Object handleCall(String methodName, Object[] args) {
if(methodName.equals("getValue1")) {
return new Integer(123);
} else if(methodName.equals("setValue")) {
...
}
...
}
}
...
IMyEntity entity = Whatever.Implement<IMyEntity>(new MyEntityDispatcher());
entity.getValue1(); // returns 123
Java Abstract class can implement interfaces without even providing the implementation of interface methods. Java Abstract class is used to provide common method implementation to all the subclasses or to provide default implementation. We can run abstract class in java like any other class if it has main() method.
The method call Proxy. newProxyInstance returns an Object created dynamically by Java during runtime time. There's no compile time processing here. The returned Object implements all interfaces provided as second argument.
Remember, a Java class can only have 1 superclass, but it can implement multiple interfaces. Thus, if a class already has a different superclass, it can implement an interface, but it cannot extend another abstract class. Therefore interfaces are a more flexible mechanism for exposing a common interface.
In Java, an abstract class can implement an interface, and not provide implementations of all of the interface's methods. It is the responsibility of the first concrete class that has that abstract class as an ancestor to implement all of the methods in the interface.
It's the Proxy
class.
class MyInvocationHandler implements InvocationHandler {
Object invoke(Object proxy, Method method, Object[] args) {
if(method.getName().equals("getValue1")) {
return new Integer(123);
} else if(method.getName().equals("setValue")) {
...
}
...
}
}
InvocationHandler handler = new MyInvocationHandler();
IMyEntity e = (IMyEntity) Proxy.newProxyInstance(IMyEntity.class.getClassLoader(),
new Class[] { IMyEntity.class },
handler);
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