Skip to main content

Type Inference and Generic Constructors of Generic Classes

No replies
Joined: 2011-07-23

I'm refering to:


<p>class MyClass<X> {<br />
   <T> MyClass(T t) {<br />
     // ...<br />
   }<br />

Consider the following examples, which are valid for Java SE 7 and later:

MyClass<Integer> myObject = new <String> MyClass<>("");

In this example, the compiler infers the type Integer for the formal type parameter, X, of the generic class MyClass<X>. The statement explicitly specifies the type String for the formal type parameter, T, of the constructor of this generic class.

Using Java 7 b147 this does NOT work for me:

<p> error: cannot infer type arguments for MyClass;<br />
MyClass<Integer> myObject = new <String>MyClass<>("");<br />
^<br />
reason: cannot use '<>' with explicit type parameters for constructor<br />
1 error</p>

Why not, what's the reasoning?

It complies of course if I use an explicit type parameter for the class "new <String>MyClass<Integer>("");" ...