Google Guice:注入原始数据结构的正确方法

时间:2019-06-24 19:46:56

标签: java guice

public class UserClassAttribute : Attribute {
}

public class Spell {
    public string name { get; set; }
    public string description { get; set; }
    [UserClass]
    public string sor { get; set; }
    [UserClass]
    public string wiz { get; set; }
    [UserClass]
    public string cleric { get; set; }
}

void BuildAccessSpellClass() {
    var members = typeof(Spell).GetProperties();
    AccessSpellClass = new Dictionary<string, Func<Spell, string>>();
    foreach (var p in members) {
        if (p.GetCustomAttribute(typeof(UserClassAttribute)) != null) {
            var className = p.Name;
            var parmS = Expression.Parameter(typeof(Spell), "s");
            var body = Expression.MakeMemberAccess(parmS, p);
            var accessExpr = Expression.Lambda<Func<Spell,string>>(body, parmS);
            AccessSpellClass.Add(className, accessExpr);
        }
    }
}

Guice会知道如何自动注入它而无需在模块中指定任何内容吗?

我担心的是,我要在专用字段中指定HashSet的类型。

1 个答案:

答案 0 :(得分:3)

您必须先将其绑定

在您的配置中:

guessedCorrect()

只有它才能注入您的let speechRec = new p5.SpeechRec('en-US', gotSpeech); function gotSpeech() { if (speechRec.resultValue) { cool = speechRec.resultString; if (cool == "0") { zero.style.color = "#dc3545"; } if (cool == "5") { five.style.color = "#dc3545"; } if (cool == "10") { ten.style.color = "#dc3545"; } if (cool == "15") { fifteen.style.color = "#dc3545"; } if (cool == "20") { twenty.style.color = "#dc3545"; } } } button.addEventListener("click", function(event) { resetround(); speechRec.start(); setTimeout("getComputerChoice()", 3000); setTimeout("identifyHands()", 3000); clearInterval(myInterval); myInterval = setInterval(function() { time--; if (time == -1) { button.innerHTML = "Again"; clearInterval(myInterval); time = 4; } else { button.innerHTML = "Start"; numbers.innerHTML = time; } }, 1000); setTimeout("guessedCorrect()", 5000); }) 中。

如果要绑定多个独立的undefined,请使用Guice的多重绑定。但是在那种情况下,您应该使用接口@Provides HashSet<WorkWindow> provideChildWorkWindows() { // Create and return your HashSet<WorkWindow> } 作为接收者,而不是CompositeWorkWindows实现,因为Guice将提供WorkWindow而不是Set。请注意,多重绑定使您可以在不同模块中具有元素的定义。

HashSet 中:

Set

HashSet 中:

MyModule.java

Multibinder<WorkWindow> workWindowBinder = Multibinder.newSetBinder(binder(), WorkWindow.class); workWindowBinder.addBinding().toInstance(new MyWorkWindow()); 中:

OtherModule.java

如果所有模块都存在于进样器中,您将得到一个大小为3的Multibinder<WorkWindow> workWindowBinder = Multibinder.newSetBinder(binder(), WorkWindow.class); workWindowBinder.addBinding().to(OtherWorkWindow.class); ,其中包含您创建的三个不同的FinalModule.java