如何摆脱 ClassCastException?
how to get rid of ClassCastException?
我正在使用 netbeans 8.1 开发一个 jsf 项目...
我的代码在这里...
Object j = u.navigate(3, u);
User nextUser;
nextUser = (User) j;
我经常遇到 ClassCastException 错误...它说 Object j cannot be cast to Entities.User 。
解决方案是重启 netbeans ,每天重启 netbeans 超过 10 次很烦人和烦躁。
我的问题是:有没有更高效的程序,或者更多
实用吗?
使用 instanceof 检查
Object j = u.navigate(3, u);
User nextUser;
if (j instanceof User) {
nextUser = (User) j;
}
正如 Samuel 所建议的,您需要在投射 class 之前拥有检查实例,因为 "you are casting down the tree"。您正在将对象 class 投射给用户 class。
对象 class 是所有 classes 的父对象。
Object j = u.navigate(3, u);
User nextUser;
if(j instanceof nextUser) {
nextUser = (User) j;
} else {
//what you need to do if not
}
我正在使用 netbeans 8.1 开发一个 jsf 项目... 我的代码在这里...
Object j = u.navigate(3, u);
User nextUser;
nextUser = (User) j;
我经常遇到 ClassCastException 错误...它说 Object j cannot be cast to Entities.User 。
解决方案是重启 netbeans ,每天重启 netbeans 超过 10 次很烦人和烦躁。
我的问题是:有没有更高效的程序,或者更多
实用吗?
使用 instanceof 检查
Object j = u.navigate(3, u);
User nextUser;
if (j instanceof User) {
nextUser = (User) j;
}
正如 Samuel 所建议的,您需要在投射 class 之前拥有检查实例,因为 "you are casting down the tree"。您正在将对象 class 投射给用户 class。 对象 class 是所有 classes 的父对象。
Object j = u.navigate(3, u); User nextUser; if(j instanceof nextUser) { nextUser = (User) j; } else { //what you need to do if not }