TypeLiteral injection with reflection

前端 未结 2 1860
抹茶落季
抹茶落季 2021-01-03 01:12

Context : java using guice (last version)

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

         


        
2条回答
  •  庸人自扰
    2021-01-03 01:50

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

    Create a TypeLiteral from it:

    TypeLiteral typeLiteral = TypeLiteral.get(type);
    

    Now create injected instance:

    return (MyClass) injector.getInstance(Key.get(typeLiteral))
    

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

    EDIT: In fact, you can use:

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

    see Guice module with type parameters

提交回复
热议问题