Google Guice + generics: Is there any magic behind the curtains?

It seems to me that the Guice implementation does some very complicated things when working with generics. It seems like at runtime he knows about the common types used at compile time. Consider a simple example:

@Inject public void Bar(Provider<Foo> genericInjector){ ... 

At run time, Guice will introduce the correct Provider implementation here (i.e. the one that provides Foo instances). But from what I know, common types are erased at runtime (see Erasure Type ). So, all that Guice really sees at runtime:

 @Inject public void Bar(Provider genericInjector){ .... 

So, how is it possible that Guice knows which Provider implementation to introduce?

+4
source share
2 answers

No, erasing a type does not erase everything. You can still get field types, parameters, etc. Provider<Foo> is still present at runtime. See Method.getGenericParameterTypes .

What is not saved is information about the type of individual objects. For example, if I write:

 List<String> list = new ArrayList<String>(); showType(list); ... public static void showType(List<?> list) { // ??? } 

It cannot be ArrayList<String> that this is an ArrayList<String> because the object no longer has this information.

See the Java Generics FAQ for more details.

+10
source

It is a common misconception that the way to erase styles is that the compiler substantially removes the angle brackets and what's inside them, and then acts as if the source were Java 1.4. This is not true.

General parameters are not erased from method signatures — method signatures are “compilation time”. General parameters do not exist in the runtime constructs - you cannot determine what type parameters the given object created.

+2
source

Source: https://habr.com/ru/post/1383119/


All Articles