2014-12-07 66 views
1

我必须使用Guice依赖注入来创建ModelWeights的对象。如何在运行时使用Guice依赖注入来绑定double[][]数组?在Guice中绑定2维数组

public class MW { 

    private double[][] weights; 
    private LogConditionalObjectiveFunction objectiveFunction; 

    @Inject 
    public MW(double[][] weights, LogConditionalObjectiveFunction func) 
    { 
     this.weights = weights; 
     this.objectiveFunction = func; 
    } 

    public double[][] getWeights() 
    { 
     return this.weights; 
    } 

    public LogConditionalObjectiveFunction getObjectiveFunction() 
    { 
     return this.objectiveFunction; 
    } 
} 

我得到这个试图几种方法:

1) No implementation for double[][] was bound. 
    while locating double[][] 
    for parameter 0 at com.data.MW.<init>(MW.java:13) 
    while locating com.data.MW 
    for parameter 0 at com.predictor.impl.MEP.<init>(MEP.java:50) 
    at  com.ServletDependencyInjector$1.configureServlets(ServletDependencyInjector.java:72) 

回答

1

使用吉斯常数结合

@Inject 
public ModelWeights(@Named("MyMatrix") double[][] weights, LogConditionalObjectiveFunction func) { 
     this.weights = weights; 
     this.objectiveFunction = func; 
} 

而在你的吉斯设置代码

@Override 
protected void configure() { 
    bind(double[][].class).annotatedWith(Names.named("MyMatrix")).toInstance(MY_MATRIX); 
} 
+0

槽糕?我发现'double [] []'[here](https://github.com/google/guice/blob/master/core/src/com/google/inject/binder/ConstantBindingBuilder.java)没有超载。只要做'bind(double [] []。class).toInstance(MY_MATRIX)' – 2014-12-07 17:38:03

+0

@TavianBarnes我猜OP更感兴趣的是绑定*常量*而不是绑定实例本身,(我提到了bindConstant的用法一些静态的,可能是最终的变量)。请参阅http://stackoverflow.com/questions/4165506/guice-difference-between-binderbindconstant-and-binderbind-toinstance – 2014-12-07 17:51:53

+0

无论如何,您的代码都不会编译。您只能使用'bindConstant()'与原语,'字符串',类'和enum's。 – 2014-12-07 23:30:23