为什么会出现这个 ClassCastException regarding Generics in Java?
Why does this ClassCastException regarding Generics in Java appear?
...以及如何修复它?
我收到以下错误:
Exception in thread "main" java.lang.ClassCastException:
java.util.LinkedList cannot be cast to java.lang.Class
at *.model.communication.GsonStream.createRequest(GsonStream.java:1)
at *.client.HttpClient.(HttpClient.java:26)
at *.client.HttpClient.main(HttpClient.java:33)
错误出现在注释行下方
HttpStream jos = new GsonStream(connection);
//...
List reqPairList = new LinkedList<Pair<String, String>>();
reqPairList.add(new Pair("username", "uname"));
reqPairList.add(new Pair("passwort", "123"));
// Exception in thread "main" java.lang.ClassCastException: java.util.LinkedList cannot be cast to java.lang.Class
jos.createRequest(reqPairList);
调用的方法和 class 如下所示:
public class GsonStream
implements HttpStream<Class<? extends Serializable>> {
//...
public void createRequest(Class<? extends Serializable> obj)
throws Exception {
//...
}
}
我对这个错误没有任何解释,特别是因为 Pair 和 LinkedList 实现了 Serializable 并且 Pair 的每个元素都被迫实现它。 (Pair是自定义的class)
我缺乏经验导致了这个错误...
修正:
public class GsonStream<E extends Serializable>
implements HttpStream<E> {
//...
public void createRequest(E obj)
throws Exception {
//...
}
}
一切正常。
...以及如何修复它?
我收到以下错误:
Exception in thread "main" java.lang.ClassCastException: java.util.LinkedList cannot be cast to java.lang.Class at *.model.communication.GsonStream.createRequest(GsonStream.java:1) at *.client.HttpClient.(HttpClient.java:26) at *.client.HttpClient.main(HttpClient.java:33)
错误出现在注释行下方
HttpStream jos = new GsonStream(connection);
//...
List reqPairList = new LinkedList<Pair<String, String>>();
reqPairList.add(new Pair("username", "uname"));
reqPairList.add(new Pair("passwort", "123"));
// Exception in thread "main" java.lang.ClassCastException: java.util.LinkedList cannot be cast to java.lang.Class
jos.createRequest(reqPairList);
调用的方法和 class 如下所示:
public class GsonStream
implements HttpStream<Class<? extends Serializable>> {
//...
public void createRequest(Class<? extends Serializable> obj)
throws Exception {
//...
}
}
我对这个错误没有任何解释,特别是因为 Pair 和 LinkedList 实现了 Serializable 并且 Pair 的每个元素都被迫实现它。 (Pair是自定义的class)
我缺乏经验导致了这个错误... 修正:
public class GsonStream<E extends Serializable>
implements HttpStream<E> {
//...
public void createRequest(E obj)
throws Exception {
//...
}
}
一切正常。