frjaeger220 / google-guice

Automatically exported from code.google.com/p/google-guice
Apache License 2.0
0 stars 0 forks source link

Injecting classes #318

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
If we could get Guice to inject concrete classes to generic classes the 
possibilities are endless:

In the example below Guice complains that it doesn't know how to create a 
Class<java.lang.String>. Surely the best thing to do is return String.class 
or Class.forName("java.lang.String"). Now I am probably missing some 
complications to do with custom class loaders but that would be a further 
enhancement to Guice.

public class TestClassInjection {
    public static class ClassInjection<T>{
        @Inject public ClassInjection(Class<T> class1){}
    }

    public static class Concrete{
        @Inject public Concrete(ClassInjection<String> concrete){}
    }
    @Test
    public void testClassInjection() throws Exception {
        Guice.createInjector().getInstance(Concrete.class);
    }
}

Original issue reported on code.google.com by NikolayM...@gmail.com on 25 Jan 2009 at 3:17

GoogleCodeExporter commented 9 years ago
Class<T> won't work in general, since there's no value for an arbitrary T. 
Consider T == List<String>. But there 
is a convenient workaround — inject a TypeLiteral<T>. That works for all 
cases and it's more powerful than 
injecting Class<T>. And conveniently, you can get the raw type of that when you 
need it.

Original comment by limpbizkit on 26 Jan 2009 at 1:15