निम्नलिखित कोड में एक सामान्य कारखाने इंजेक्शन एक कारखाने है कि एक Bar<T>
का उत्पादन एक Foo<T>
दिया का एक उदाहरण है। कारखाने परवाह नहीं है कि T
है: किसी भी प्रकार के T
के लिए, यह Foo<T>
से Bar<T>
बना सकता है।Guice
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);
}
}
जब मैं कोड चलाने के लिए, मैं 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.
केवल संदर्भ मैं Guice दस्तावेज में जेनरिक के लिए मिल सकता है एक TypeLiteral
उपयोग करने के लिए कहते हैं। लेकिन मेरे पास शाब्दिक प्रकार नहीं है, मेरे पास एक सामान्य प्लेसहोल्डर है जो कारखाने के लिए प्रासंगिक नहीं है। कोई सुझाव?
बारफैक्टरी सामान्य नहीं है, इसलिए इसे जिस तरह से मैंने तार दिया है उसे तार करने के लिए यह सही समझ में आता है। बार के एक पैरामिट्रीकृत उदाहरण अनुबंध से मेल खाएंगे नहीं: एक फू लेने के लिए करने के लिए की जरूरत है बना सकते हैं और एक बार वापसी किसी भी टी –