This question already has an answer here:
这个问题已经有了答案:
- ClassCast error: Java 7 vs Java 8 1 answer
- ClassCast错误:Java 7 vs Java 8 1答案
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
在java 7上,这很好,但是在java 8上我得到了java.lang。ClassCastException:. lang。不能将字符串转换为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.
get(DomainField.ZIP)应该返回字符串,它是,但是它不能被转换为MValue,我不知道为什么?有人能给我解释或推荐一些文件吗?谢谢。
1 个解决方案
#1
2
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.
在这里,我明确地将T的类型指定为字符串,但是类型检查仍然会发生,但是它清楚地告诉编译器什么是期望的。这个调用应该适用于Java 7和8。
#1
2
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.
在这里,我明确地将T的类型指定为字符串,但是类型检查仍然会发生,但是它清楚地告诉编译器什么是期望的。这个调用应该适用于Java 7和8。