Google Guice +泛型:窗帘背后是否有魔法?(Google Guice + generics: Is there some magic behind the curtains?)

编程入门 行业动态 更新时间:2024-10-27 16:24:35
Google Guice +泛型:窗帘背后是否有魔法?(Google Guice + generics: Is there some magic behind the curtains?)

在我看来,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.

更多推荐

本文发布于:2023-08-07 00:43:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1459532.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:窗帘   魔法   泛型   Google   Guice

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!