通过方法获取 TypeLiterals 以减少冗长

Getting TypeLiterals via method to reduce verbosity

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

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

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

我建议您以编程方式创建 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) {
    }
}