Java guice将类型绑定到未知类型,但类型匹配

Java guice将类型绑定到未知类型,但类型匹配,java,scala,guice,Java,Scala,Guice,我试图从属性映射绑定一组类型,其中键的类型是String,映射中的值的类型是String、Boolean、Int、Long等等,甚至是某种类型的对象 这在scala中,但同样适用于java class GuiceFlagsModule( flags: Map[String, Any]) extends AbstractModule with Logging { def configure() { for ((flagName

我试图从属性映射绑定一组类型,其中键的类型是String,映射中的值的类型是String、Boolean、Int、Long等等,甚至是某种类型的对象

这在scala中,但同样适用于java

   class GuiceFlagsModule(
      flags: Map[String, Any])
      extends AbstractModule
      with Logging {

      def configure() {
        for ((flagName, flag) <- flags) {
          debug("Binding flag: " + flagName + " = " + flag)
          val key2 = Key.get(value.getClass, new FlagImpl(flagName))
          binder.bind(key2).toInstance(value)
        }
      }
    }
如何编译它,使其正确绑定泛型类型

我刚刚在java中试过,它似乎在intellij中工作,但在javac编译器上失败了:(

那么如何在java或scala中实现这一点呢

我设法让它像这样在java中工作

public static void bind(Binder binder, String flagName, Object value) {
    Key<Object> key = Key.get((Class) value.getClass(), new FlagImpl(flagName));
    binder.bind(key).toInstance(value);
}
publicstaticvoidbind(绑定器绑定器、字符串标记名、对象值){
Key=Key.get((Class)value.getClass(),new-FlagImpl(flagName));
活页夹.bind(键).toInstance(值);
}
我仍然没有它在scala中工作

谢谢,
Dean

您需要确保
键的类型参数与
值的类型匹配

坏消息是:我不知道有什么安全的方法可以做到这一点,至少在一般情况下是这样。好消息是,使用未经检查的强制转换可以很容易地做到。我对Scala不太了解,不能肯定,但在Java中,我会这样写:

public static <T> void bind(Binder binder, String flagName, T value) {
  @SuppressWarnings("unchecked")
  Class<T> valueClass = (Class) value.getClass();
  Key<T> key = Key.get(valueClass, new FlagImpl(flagName));
  binder.bind(key).toInstance(value);
}

但这当然只是把问题推给了打电话的人。

发布的解决方案对我不起作用:

public static void bind(Binder binder, String flagName, Object value) {
    Key<Object> key = Key.get((Class) value.getClass(), new FlagImpl(flagName));
    binder.bind(key).toInstance(value);
}
public static <T> void bind(Binder binder, String flagName, T value) {
  @SuppressWarnings("unchecked")
  Class<T> valueClass = (Class) value.getClass();
  Key<T> key = Key.get(valueClass, new FlagImpl(flagName));
  binder.bind(key).toInstance(value);
}
public static <T> void bind(
    Binder binder, String flagName, Class<T> valueClass, T value) {
  Key<T> key = Key.get(valueClass, new FlagImpl(flagName));
  binder.bind(key).toInstance(value);
}
public static void bind(Binder binder, String flagName, Object value) {
    Key<Object> key = Key.get((Class) value.getClass(), new FlagImpl(flagName));
    binder.bind(key).toInstance(value);
}
Class impl = ...
Class intrf = ...
binder.bind(intrf).to(impl);