TypeLiteral注射反射

ove*_*low 6 java guice

上下文:java使用guice(最新版本)

大家好,是否可以通过这种方式向Guice注入一些TypeLiteral:

public MyClass<?,?> getMyClass(Injector injector, Class<?> a, Class<?> b)
{
     //how to Inject MyClass with type a & b ?
     //e.g : injector.getInstance(MyClass<"a class","b class">)
}

public interface MyClass<S,T>
{
     public T do(S s);
}

public class ClassOne implements MyClass<String,Integer>
{
     public Integer do(String s)
     {
          //do something
     }
}

Module :
bind.(new TypeLiteral<MyClass<String,Integer>(){}).to(ClassOne.class);
bind.(new TypeLiteral<MyClass<String,Double>(){}).to(ClassTwo.class);
...
Run Code Online (Sandbox Code Playgroud)

处理这个问题的最佳方法是什么(使用Guice)?

谢谢 !

ysd*_*sdx 3

为您的类型创建 ParameterizeType :

// It's supposed to be internal.
// You could use sun.reflect.generics.reflectiveObjects but it is not portable.
// Or you can implement it yourself (see below)
ParameterizedType type = new com.google.inject.internal.MoreTypes.ParameterizedTypeImpl(null, MyClass.class, a, b);
Run Code Online (Sandbox Code Playgroud)

从它创建一个 TypeLiteral:

TypeLiteral typeLiteral = TypeLiteral.get(type);
Run Code Online (Sandbox Code Playgroud)

现在创建注入实例:

return (MyClass<A,B>) injector.getInstance(Key.get(typeLiteral))
Run Code Online (Sandbox Code Playgroud)

在实践中,您想自己实现 ParameteriedType:

 final Type[] types = {a, b};
 ParameterizedType type = ParameterizedType() {
   @Override
   public Type[] getActualTypeArguments() {
     return types;
   }

   @Override
   public Type getOwnerType() {
     return null;
   }

   @Override
   public Type getRawType() {
     return MyClass.class;
   };
}
Run Code Online (Sandbox Code Playgroud)

编辑:事实上,您可以使用:

Types.newParameterizedType(MyClass.class,a,b)
Run Code Online (Sandbox Code Playgroud)

请参阅带有类型参数的 Guice 模块