【问题标题】:Getting TypeLiterals via method to reduce verbosity通过方法获取 TypeLiterals 以减少冗长
【发布时间】:2021-10-22 13:52:57
【问题描述】:

我想减少将泛型接口绑定到基于 TypeLiterals 的多个实现的冗长...
我有一个接口FieldComputer<T extends ComputeField>,其中ComputeField 是我的模型接口。

尝试扩展 ShortLiteral 类(参见下面的示例)以减少冗长,但它似乎不起作用。想知道为什么?

// A typical Guice Module
public class ConflationModule implements Module {

  // typical overridden configure method
  public void configure(Binder binder) {

    // Works but is verbose....
    bindField_1(binder,
                new TypeLiteral<FieldComputer<ComputeFieldImpl>>(){},
                FieldComputerImpl.class);

    // Doesn't Work
    bindField_1(binder, 
                new ShortLiteral<ComputeFieldImpl>(){}, 
                FieldComputerImpl.class);

    // Doesn't Work
    bindField_2(binder, 
                new ShortLiteral<ComputeFieldImpl>(){}, 
                FieldComputerImpl.class);

  }

  private static class ShortLiteral<CF extends ComputeField> extends TypeLiteral<FieldComputer<CF>>{}

  private <CF extends ComputeField> void bindField_1(Binder binder,
            TypeLiteral<FieldComputer<CF>> typeLiteral,
            Class<? extends FieldComputer<CF>> clazz
  ) {
        binder.bind(typeLiteral).to(clazz);
  }

  private <CF extends ComputeField> void bindField_2(Binder binder,
            ShortLiteral<CF> typeLiteral,
            Class<? extends FieldComputer<CF>> clazz
  ) {
        binder.bind(typeLiteral).to(clazz);
  }
}

【问题讨论】:

    标签: dependency-injection guice typeliteral


    【解决方案1】:

    我建议您以编程方式创建TypeLiteral,这里有一个示例如何使用一个接口的不同实现来实现:

    class TypeLiteralModule extends AbstractModule {
        @Override
        protected void configure() {
            customBind(String.class, StringConsumer.class);
            customBind(Integer.class, IntegerConsumer.class);
        }
    
        private <T> void customBind(Class<T> clazz, Class<? extends Consumer<T>> impl) {
            var typeLiteral = (TypeLiteral<Consumer<T>>) TypeLiteral.get(Types.newParameterizedType(Consumer.class, clazz));
            bind(impl).in(Singleton.class);
            bind(typeLiteral).to(impl);
        }
    }
    
    class StringConsumer implements Consumer<String> {
        @Override
        public void accept(String s) {
        }
    }
    
    class IntegerConsumer implements Consumer<Integer> {
        @Override
        public void accept(Integer s) {
        }
    }
    

    【讨论】:

    • 这正是我想要的...谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-10
    相关资源
    最近更新 更多