Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
751 views
in Technique[技术] by (71.8m points)

java - Injecting a generic factory in Guice

The following code is an example of a factory that produces a Bar<T> given a Foo<T>. The factory doesn't care what T is: for any type T, it can make a Bar<T> from a Foo<T>.

import com.google.inject.*;
import com.google.inject.assistedinject.*;

class Foo<T> {
  public void flip(T x) { System.out.println("flip: " + x); }
}

interface Bar<T> {
  void flipflop(T x);
}

class BarImpl<T> implements Bar<T> {
  Foo<T> foo;

  @Inject
  BarImpl(Foo<T> foo) { this.foo = foo; }

  public void flipflop(T x) { foo.flip(x); System.out.println("flop: " + x); }
}

interface BarFactory {
  <T> Bar<T> create(Foo<T> f);
}

class Module extends AbstractModule {
  public void configure() {
    bind(BarFactory.class)
      .toProvider( 
          FactoryProvider.newFactory( BarFactory.class, BarImpl.class ) 
                   );
  }
}

public class GenericInject {
  public static void main(String[] args) {
    Injector injector = Guice.createInjector(new Module());

    Foo<Integer> foo = new Foo<Integer>();
    Bar<Integer> bar = injector.getInstance(BarFactory.class).create(foo);
    bar.flipflop(0);
  }
}

When I run the code, I get the following errors from Guice:

1) No implementation for BarFactory was bound.
  at Module.configure(GenericInject.java:38)

2) Bar<T> cannot be used as a key; It is not fully specified.

The only reference I can find to generics in the Guice documentation says to use a TypeLiteral. But I don't have a literal type, I have a generic placeholder that isn't relevant to the factory at all. Any tips?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One option is to just write the BarFactory boilerplate by hand:

class BarImplFactory implements BarFactory {
  public <T> Bar<T> create(Foo<T> f) {
    return new BarImpl(f);
  }
}

The binding becomes

bind(BarFactory.class).to(BarImplFactory.class);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...