Programmatically implementing an interface that combines some instances of the same interface in var

Posted by namin on Stack Overflow See other posts from Stack Overflow or by namin
Published on 2010-05-22T00:29:25Z Indexed on 2010/05/22 0:30 UTC
Read the original article Hit count: 534

What is the best way to implement an interface that combines some instances of the same interface in various specified ways? I need to do this for multiple interfaces and I want to minimize the boilerplate and still achieve good efficiency, because I need this for a critical production system.

Here is a sketch of the problem.

Abstractly, I have a generic combiner class which takes the instances and specify the various combinators:

class Combiner<I> {
   I[] instances;

   <T> T combineSomeWay(InstanceMethod<I,T> method) {
     // ... method.call(instances[i]) ... combined in some way ...
   }

   // more combinators
}

Now, let's say I want to implement the following interface among many others:

Interface Foo {
  String bar(int baz);
}

I want to end up with code like this:

class FooCombiner implements Foo {
  Combiner<Foo> combiner;

  @Override 
  public String bar(final int baz) {
    return combiner.combineSomeWay(new InstanceMethod<Foo, String> {
      @Override public call(Foo instance) { return instance.bar(baz); } 
    });
  }
}

Now, this can quickly get long and winded if the interfaces have lots of methods. I know I could use a dynamic proxy from the Java reflection API to implement such interfaces, but method access via reflection is hundred times slower. So what are the alternatives to boilerplate and reflection in this case?

© Stack Overflow or respective owner

Related posts about java

Related posts about code-generation