mentics
mentics

Reputation: 6999

Wrapping a Class<?> type generics error

I'm not following why this code shows this compile error.

Error is:

Type mismatch: cannot convert from TestClass.Wrapper<List<capture#1-of ?>> to TestClass.Wrapper<List<?>>

Code is below.

package test.cls;

import java.util.List;

public class TestClass
{
    static abstract class Wrapper<A>
    {
        public abstract A wrapped();
    }

    public static <A> Wrapper<A> wrap(final A val)
    {
        return new Wrapper<A>()
        {
            public A wrapped()
            {
                return val;
            }
        };
    }

    public static void main(final String[] args)
    {
        final List<?> list = null;
        final Class<?> c = null;
        final Wrapper<List<?>> wrapList = wrap(list); // Error here
        final Wrapper<Class<?>> wrapC = wrap(c); // Error here
    }
}

Upvotes: 1

Views: 346

Answers (1)

Paul Bellora
Paul Bellora

Reputation: 55233

The compiler's generic type inferrence is choking on the nested wildcard captures. You need to explicitly specify the type arguments:

final Wrapper<List<?>> wrapList = TestClass.<List<?>>wrap(list);
final Wrapper<Class<?>> wrapC = TestClass.<Class<?>>wrap(c);

Upvotes: 5

Related Questions