Wednesday, 15 September 2010

type erasure - Java 8 - Generic Supplier -


Today I tried a constructor in generic Why is it wrong?

import java.util.Collection; Import java.util.function.Supplier; Square fu & lt; R archive expansion & lt; Integer & gt; & Gt; {Supplier & lt; R & gt; Supplier = R: New; // Compiler Error! }

Error text:

  java: unexpected type required: class or array found: type parameter R  

Is this the reason? Or maybe I am doing this wrong?

By compiling the time, you are bound to all of R ; That this archive & lt; Integer & gt; There is a subtype of . You do not know which class corresponds with R but you are trying to refer to the constructor - and to refer to the constructor, you have to know which class you want to build All of the following will be unable to work for the same reason: It is not known what is R, and you need to know how R will call its Constructor.

  Supplier & lt; R & gt; Supplier = R :: New Supplier & lt; R & gt; Supplier = () - & gt; New r (); RR = new R ();  

It would also be true, if R is to & lt; Has been declared as R; ArrayList & lt; String & gt; & Gt; In this case, you can know that R array list & lt; String & gt; , but you do not even know which class it belongs to!

If you select collections & lt; Integer & gt; , then this would work:

  ToIntFunction & lt; R & gt; Sizer = R: size;  

Because, whatever is R , there should be a size () method.


No comments:

Post a Comment