Java Reference
In-Depth Information
package
stripesbook.ext;
public class
MyActionBeanContext
extends
ActionBeanContext {
private static final
String FOLDER = "folder";
public void
setCurrentFolder(Folder folder) {
setCurrent(FOLDER, folder);
}
public
Folder getCurrentFolder() {
Folder folder = MockFolderDao.getInstance().read().get(0);
return
getCurrent(FOLDER, folder);
}
protected void
setCurrent(String key, Object value) {
getRequest().getSession().setAttribute(key, value);
}
@SuppressWarnings("unchecked")
protected
<T> T getCurrent(String key, T defaultValue) {
T value = (T) getRequest().getSession().getAttribute(key);
if
(value ==
null
) {
value = defaultValue;
setCurrent(key, value);
}
return
value;
}
}
All we need to do now is adjust the getter and setter methods in
BaseAc-
tionBean
so that they use
MyActionBeanContext
. That way, the cast of
ActionBeanContext
to
MyActionBeanContext
is done in only one place:
package
stripesbook.action;
public abstract class
BaseActionBean
implements
ActionBean {
private
MyActionBeanContext context;
public
MyActionBeanContext getContext() {
return
context;
}
public void
setContext(ActionBeanContext context) {
this
.context = (MyActionBeanContext) context;
}
}
Notice that we're using a feature introduced in the JDK 1.5, which
is to allow overriding a method (
getContext
( )) and returning an object
whose type (
MyActionBeanContext
) is a subclass of the type returned by
the superclass (
ActionBeanContext
). This removes the need for casting
to
MyActionBeanContext
elsewhere in the codeāthe only cast is in the
setContext
( ) method.
Search WWH ::
Custom Search