xatkit-runtime
xatkit-runtime copied to clipboard
Add typed getter for session
Session is implemented as a Map<Object, Object>
, so we have a single way to access session values: session.get(key)
, which returns an Object
.
Most of the time we know what we are storing in the session though, and we have to cast the result of get
:
String myString = (String) context.getSession().get("myKey");
While this is fine for simple types it is annoying for complex ones, especially when accessed in transitions where we typically want a compact syntax:
myState.body(...)
.next()
.when(((MyComplexType)context.getSession().get("myKey")).getX() == 2).moveTo(...)
This could be simplified by implementing typed getters for the session:
myState.body(...)
.next()
.when(context.getSession().get("myKey", MyComplexType.class).getX() == 2).moveTo(...)
Additional getters could be provided for basic types: getAsString
, getAsInt
, etc
See this piece of code:
private static class MyMap<K, V> extends HashMap<K, V> {
public String getAsString(K key) {
return get(key, String.class);
}
public Integer getAsInt(K key) {
return get(key, Integer.class);
}
public <T> T get(K key, Class<T> type) {
Object o = this.get(key);
return (T) o;
}
}