我从这里关注Guice文档:
http://code.google.com/p/google-guice/

我被困在toProvider方法上。当我尝试这样做时:

bind(Shape.class).toProvider(ShapeProvider.class);

我收到此错误:

The method toProvider(Provider<? extends Shape>) in the type LinkedBindingBuilder<Shape> is not applicable for the arguments (Class<ShapeProvider>)

我的代码如下:

配置类

public class Configuration extends AbstractModule{
    @Override
    protected void configure(){
        bind(Shape.class).toProvider(ShapeProvider.class);
        bind(Triangle.class).to(IsoTriangle.class);
    }


ShapeProvider类

public class ShapeProvider implements Provider<Shape> {
    private int length;
    @Inject
    public ShapeProvider(int length){
        this.length = length;
    }
    public Shape get(){
        Shape triangle = new Triangle(length);
        return triangle;

    }
}


形状界面

public interface Shape {

}


三角课

public class Triangle implements Shape{
    int length;
    public Triangle(){
    }
    public Triangle(int lenght){
        this.length = lenght;
    }
}


我会错过某些东西还是文档中没有提到的东西?

更新:

提供者接口:

public interface Provider<T> {
    T get();
}

最佳答案

如果使用toProvider,则必须提供一个Provider实例。请参见LinkedBindingBuilder.toProvider的javadoc

bind(Shape.class).toProvider(new ShapeProvider());


或者您应该使用将类作为参数的to。另请参见LinkedBindingBuilder.to()的javadoc

bind(Shape.class).to(ShapeProvider.class);


编辑

我无法重现您的问题。我创建了一些类来模拟问题(因为我现在不想设置guice),但是据我所知……没有编译器错误。

以下代码与guice api类型等效,并且可以编译。

public class Main {

    public static void main(String[] args) {
        LinkedBindingBuilder<Shape> linkedBindingBuilder = new LinkedBindingBuilder<Shape>();
        linkedBindingBuilder.toProvider(new ShapeProvider());
    }

    public static class ShapeProvider implements Provider<Shape> {
        public Shape get() {return null;}
    }

    public static class Shape {}

    public static class LinkedBindingBuilder<T> {

        public ScopedBindingBuilder toProvider(Provider<? extends T> provider) {
            return null;
        }
    }

    private static interface Provider<T> {
        T get();
    }

    private static class ScopedBindingBuilder {}
}

07-26 03:59