0

I know how to workaround this problem, but still looking for knowledge of concept why the below problem arises.

import org.junit.Test;

import java.util.Arrays;
import java.util.List;


public class TypeTest {

    class TypedClass<TYPEA, TYPEB> {
        private Integer value = 1;

        public List<Integer> getValueAsList() {
            return Arrays.asList(value);
        }
    }

    @Test
    public void testType() {
        TypedClass typedClassWithOutTypeInfo = new TypedClass();
        TypedClass<?,?> typedClassWithTypeInfo = new TypedClass();

        System.out.println(typedClassWithOutTypeInfo.getValueAsList().stream().findFirst().get().intValue()); //ERROR. get() returns Object rather than Integer
        System.out.println(typedClassWithTypeInfo.getValueAsList().stream().findFirst().get().intValue()); //Works.

    }
}

NutShell: Even though the method returnType does not depend on classType, it's lost if class is declared without typeInfo.

  • It's because `typedClassWithOutTypeInfo` is a raw type, and so *all* generic information lost, not simply the generics relating to the omitted type variables. Don't use raw types. – Andy Turner Jul 14 '17 at 10:58
  • Also: don't use raw types on the RHS of the assignment either: `new TypedClass<>();`. – Andy Turner Jul 14 '17 at 11:01

0 Answers0