我们有一个类 User 与 Preference 具有一对一的关系(该属性称为 storedPreference)。假设用户将 CustomPreference(Preference 的子类)的一个实例保存为它的 storedPreference。获取 storedPreference 并将其转换为 CustomPreference 会导致 ClassCastException 但为什么呢?
(CustomPreference)theUser.getStoredPreference()
原因
java.lang.ClassCastException: core.preferences.Preferences_$$_javassist_82 cannot be cast to hb.core.preferences.CustomPreferences
at hb.base.user.user.HadithUser.getPreferences(HadithUser.java:39)
at hb.base.user.user.HadithUser.getPreferences(HadithUser.java:23)
at core.form.base.ThemeForm.getTheme(ThemeForm.java:116)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at javax.el.BeanELResolver.getValue(BeanELResolver.java:87)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:67)
at org.apache.myfaces.el.unified.resolver.FacesCompositeELResolver.getValue(FacesCompositeELResolver.java:179)
at org.apache.el.parser.AstValue.getValue(AstValue.java:183)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:185)
at org.primefaces.renderkit.HeadRenderer.encodeBegin(HeadRenderer.java:85)
at javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:587)
at javax.faces.component.UIComponentBase.encodeAll(UIComponentBase.java:517)
at javax.faces.component.UIComponentBase.encodeAll(UIComponentBase.java:541)
at org.apache.myfaces.view.facelets.FaceletViewDeclarationLanguage.renderView(FaceletViewDeclarationLanguage.java:1981)
at org.apache.myfaces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:298)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:59)
at org.apache.myfaces.tomahawk.application.ResourceViewHandlerWrapper.renderView(ResourceViewHandlerWrapper.java:93)
at org.springframework.faces.webflow.FlowViewHandler.renderView(FlowViewHandler.java:99)
at org.apache.myfaces.lifecycle.RenderResponseExecutor.execute(RenderResponseExecutor.java:116)
at org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:241)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:199)
... 84 more
以下是实体定义:
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Preferences {
...
}
@Entity
public class CustomPreferences extends Preferences {
...
}
@Entity
public class User {
@OneToOne(fetch = FetchType.LAZY)
public Preferences getStoredPreferences() {
return storedPreferences;
}
...
}
我检查了数据库以确保此实例的 DTYPE 值是 CustomPreference 并且它是正确的