Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic implementation for interface/abstract class in Java

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
like image 259
Andrey Agibalov Avatar asked Aug 02 '11 15:08

Andrey Agibalov


People also ask

Can we implement interface in abstract class in Java?

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.

How do you implement an interface dynamically in Java?

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.

Can a class extend an abstract class and implement an interface?

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.

Should an abstract class implement an 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.


1 Answers

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);
like image 154
Joachim Sauer Avatar answered Nov 14 '22 14:11

Joachim Sauer