在我看来,Guice的实现在处理泛型时做了一些非常棘手的事情。 它看起来在运行时知道编译时使用的泛型类型。 我们来看一个简单的例子:
@Inject public void Bar(Provider<Foo> genericInjector){ ...在运行时,Guice将在这里注入Provider的正确实现(即提供Foo实例的实例)。 但据我所知,泛型类型在运行时会被擦除 (请参阅: 类型擦除 )。 所以Guice在运行时真正看到的是:
@Inject public void Bar(Provider genericInjector){ ....那么Guice怎么可能知道Provider要注入哪个实现呢?
It seems to me that Guice implementation is doing some very tricky things when dealing with generics. It looks like it knows at runtime about generic types used at compile time. Let's see a simple example:
@Inject public void Bar(Provider<Foo> genericInjector){ ...At runtime Guice will inject a correct implementation of Provider here (i.e. the one that provides Foo instances). But from what I know, generic types are erased at runtime (see: Type Erasure ). So all that Guice really sees at runtime is:
@Inject public void Bar(Provider genericInjector){ ....So how is it possible that Guice knows which implementation of Provider to inject?
最满意答案
不,类型擦除不会擦除所有内容 。 您仍然可以获取字段类型,参数等Provider<Foo>信息在执行时仍然存在。 例如,请参阅Method.getGenericParameterTypes 。
不保留的是关于特定对象的类型信息。 例如,如果我写:
List<String> list = new ArrayList<String>(); showType(list); ... public static void showType(List<?> list) { // ??? }没有办法可以算出它是一个ArrayList<String>因为对象不再有这些信息。
有关更多信息,请参阅Java泛型常见问题解答 。
No, type erasure doesn't erase everything. You can still get the types of fields, parameters etc. The Provider<Foo> information is still present at execution time. See Method.getGenericParameterTypes for example.
What isn't preserved is the type information about specific objects. For example, if I write:
List<String> list = new ArrayList<String>(); showType(list); ... public static void showType(List<?> list) { // ??? }There's no way that can work out that it's an ArrayList<String> because the object doesn't have that information any more.
See the Java Generics FAQ for a lot more information.
更多推荐
发布评论