使用: Guice 3
我想知道如何从泛型方法TypeLiteral (将它注入注入器)创建一个。
以下是一个例子:
背景:
bind(new TypeLiteral<Set<String>>(){}).toInstance(x);
bind(new TypeLiteral<Set<Integer>>(){}).annotatedWith(INJECTOR.class).toInstance(y);public class Foo
{
public void bar(Injector injector, Set<String> param, @INJECTOR Set<Integer> value)
{
//...
}
}public class Example
{
@Inject
Injector injector;
public void methodInjector()
{
Method[] fooMethods = Foo.class.getMethods();
for(Method m : fooMethods)
{
for(Class<?> c : m.getParameter.getParameterTypes())
{
Object o = injector.getInstance(c);
/*
this work for simple Type like "Injector" but
don't work for generic type (Set<String>, List<Set<String>>, ...).
*/
}
}
}
}显然注射java.util.Set在我的情况下行不通.也许TypeLiteral有个诀窍.
我希望我的解释清楚,谢谢。
发布于 2012-04-29 18:34:57
我找到了一个使用TypeLiteral.getParameterTypes(成员)的解决方案
发布于 2012-04-29 10:00:30
正如我正确理解您的这里一样,您已经解释了如何在运行时访问泛型类型。如果要获取所有类的参数类型,则为不可能。
https://stackoverflow.com/questions/10371048
复制相似问题