从泛型方法parameterType创建TypeLiteral

时间:2012-04-29 09:23:18

标签: java guice

使用:Guice 3

我想知道如何从通用方法parameterType创建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有一个技巧可以做到......

我希望我的解释清楚, 感谢。

2 个答案:

答案 0 :(得分:0)

正如我理解你here,你已经解释了如何在运行时访问泛型类型。如果要获取所有类的参数类型,请impossible

答案 1 :(得分:0)

我找到了使用TypeLiteral.getParameterTypes(Member)

的解决方案