Guice SPI: find bindings by wildcard types

…衆ロ難τιáo~ 提交于 2019-12-04 14:17:50

Unfortunately, there's no out-of-the-box API that will tell you whether one TypeLiteral is assignable from another. You'll need to do an old-school loop with a bunch of hideous instanceof checks. Something gross like this:

for (Map.Entry<Key<?>, Binding<?>> entry 
    : injector.getBindings().entrySet()) {
  Type type = entry.getKey().getTypeLiteral().getType();
  if (!(type instanceof ParameterizedType)) continue;

  ParameterizedType parameterized = (ParameterizedType) type;
  if (parameterizedType.getRawType() != Foo.class) continue;

  Type parameter = .getActualTypeArguments()[0]
  if (!(parameter instanceof Class)) continue;

  Class<?> parameterClass = (Class<?>) parameter;
  if (!Bar.class.isAssignableFrom(parameterClass)) continue;

  results.add(entry);
}

Of course, it would be much nicer to do something using an off-the-shelf API. I'd welcome an contribution to Guice that implements and tests TypeLiteral.isAssignableFrom(TypeLiteral). Contact our user's list to volunteer!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!