类型带反射的文学注入 [英] TypeLiteral injection with reflection

查看:126
本文介绍了类型带反射的文学注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Context : java using guice (last version)

大家好,是否可以通过Guice注入一些TypeLiteral:

Hi everybody, is it possible to inject some TypeLiteral with Guice by this way :

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);
...

(使用Guice)解决此问题的最佳方法是什么?

What is the best way to handle this problem (with Guice)?

谢谢!

推荐答案

为您的类型创建ParameterizeType:

Create a ParameterizeType for your type :

// 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);

从中创建TypeLiteral:

Create a TypeLiteral from it:

TypeLiteral typeLiteral = TypeLiteral.get(type);

现在创建注入的实例:

return (MyClass<A,B>) injector.getInstance(Key.get(typeLiteral))

实际上,您想自己实现ParameteriedType:

In practice you want to implement the ParameteriedType yourself:

 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;
   };
}

实际上,您可以使用:

Types.newParameterizedType(MyClass.class,a,b)

请参见具有类型参数的Guice模块

这篇关于类型带反射的文学注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆