【发布时间】:2011-08-17 17:30:51
【问题描述】:
我收到了一些 CastClassExceptions。我认为我对子类化的理解很困惑,可以使用一些澄清。我有以下课程:
// defined in java.util
abstract class ResourceBundle {
...
}
// defined in java.util
class PropertyResourceBundle extends ResourceBundle {
...
}
// defined by myself
class ResourceBundleWrapper extends ResourceBundle {
...
// abstract in ResourceBundle
@Override public Enumeration<String> getKeys() {
throw new UnsupportedOperationException();
}
// abstract in ResourceBundle
@Override protected Object handleGetObject(String key) {
throw new UnsupportedOperationException();
}
// protected in ResourceBundle
public Set<String> handleKeySet() {
...
the code from ResourceBundle.handleKeySet()
...
}
...
}
包装类的目的是公开handleKeySet() 方法,这样我就可以获取包的密钥,而无需另外获取其父包的密钥。 我大致有以下代码:
ResourceBundle bundle = getBundle(); // method can return any subclass of ResourceBundle
我希望能够通过将其转换为 ResourceBundleWrapper 来获取 bundle 的键。如果没有 ClassCastException,我无法将 bundle 转换为类型 ResourceBundleWrapper。错误信息示例:
java.util.PropertyResourceBundle cannot be cast to com.common.ResourceBundleWrapper
我明白为什么会发生这种演员表异常。这不是我需要澄清的。我如何通过这种方法实现我想要实现的目标?
【问题讨论】:
标签: java inheritance subclassing resourcebundle