Type cast access for ext state variables.
This commit is contained in:
@@ -34,4 +34,13 @@ public interface ExtendedState {
|
||||
*/
|
||||
Map<Object, Object> getVariables();
|
||||
|
||||
/**
|
||||
* Gets a variable which is automatically casted into a type.
|
||||
*
|
||||
* @param key the variable key
|
||||
* @param type the variable type
|
||||
* @return the variable
|
||||
*/
|
||||
<T> T get(Object key, Class<T> type);
|
||||
|
||||
}
|
||||
|
||||
@@ -42,4 +42,18 @@ public class DefaultExtendedState implements ExtendedState {
|
||||
return variables;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public <T> T get(Object key, Class<T> type) {
|
||||
Object value = this.variables.get(key);
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
if (!type.isAssignableFrom(value.getClass())) {
|
||||
throw new IllegalArgumentException("Incorrect type specified for variable '" +
|
||||
key + "'. Expected [" + type + "] but actual type is [" + value.getClass() + "]");
|
||||
}
|
||||
return (T) value;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -166,16 +166,16 @@ public class Application {
|
||||
@Override
|
||||
public void execute(StateContext<States, Events> context) {
|
||||
Map<Object, Object> variables = context.getExtendedState().getVariables();
|
||||
Object foo = variables.get("foo");
|
||||
if (foo instanceof Integer && ((Integer)foo) == 0) {
|
||||
Integer foo = context.getExtendedState().get("foo", Integer.class);
|
||||
if (foo == null) {
|
||||
log.info("Init foo to 0");
|
||||
variables.put("foo", 0);
|
||||
} else if (foo == 0) {
|
||||
log.info("Switch foo to 1");
|
||||
variables.put("foo", 1);
|
||||
} else if (foo instanceof Integer && ((Integer)foo) == 1) {
|
||||
} else if (foo == 1) {
|
||||
log.info("Switch foo to 0");
|
||||
variables.put("foo", 0);
|
||||
} else {
|
||||
log.info("Init foo to 0");
|
||||
variables.put("foo", 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user