Search code examples
javagenericsjava-8java-7classcastexception

ClassCastException String to MValue, java 8


I have an interface

public interface MValue extends SomeOtherInterface, Serializable

and I use it in another interface like so

    public interface DomainObject extends Iterable<FieldValueAssociation>, Cloneable, Serializable {
     void add(DomainField field, MValue... values);
<T> T get(DomainField field);
    }

and when I call this in some other class I set

subDomain.add(DomainField.ZIP, d.get(DomainField.ZIP));

On java 7 this works fine, but on java 8 I get java.lang.ClassCastException: java.lang.String cannot be cast to net.blabla.domain.MValue

d.get(DomainField.ZIP) should return String, and it is, but it cannot be casted to MValue, and I dont know why? Can someone explain or refer me to some documentation. Thanks.


Solution

  • So does that work?

    subDomain.add(DomainField.ZIP, d.<String>get(DomainField.ZIP));
    

    Here I explicitly give the type for T as being String, type checking will happen nevertheless, but it makes clear to the compiler what is expected. This call should work for Java 7 and 8.