/** * Looks up a state of the specified (sub)type if it exists. If there exist * multiple the first encountered is returned. * @param type The (sub)type to look for. * @param <U> The type. * @return The state of the specified type. * @throws IllegalArgumentException if there is no state of the specified * type. */ public <U> U getStateOfType(Class<U> type) { for (final State<T, C> state : getStates()) { if (type.isInstance(state)) { return type.cast(state); } } throw new IllegalArgumentException("There is no instance of " + type + " in this state machine."); }
/** * Looks up a state of the specified (sub)type if it exists. If there exist * multiple the first encountered is returned. * @param type The (sub)type to look for. * @param <U> The type. * @return The state of the specified type. * @throws IllegalArgumentException if there is no state of the specified * type. */ public <U> U getStateOfType(Class<U> type) { for (final State<T, C> state : getStates()) { if (type.isInstance(state)) { return type.cast(state); } } throw new IllegalArgumentException("There is no instance of " + type + " in this state machine."); }
/** * Tests the query by class method. */ @Test public void testGetStateOfType() { final StateA a = new StateA(); final StateB b = new StateB(); final StateC c = new StateC(); final StateMachineBuilder<Events, Context> smb = StateMachine.create(a) .addTransition(a, Events.START, b) .addTransition(b, Events.START, c) .addTransition(c, Events.START, a); if (explicitRecursiveTransitions) { smb.explicitRecursiveTransitions(); } fsm = smb.build(); final State<Events, Context> first = fsm.getStates().iterator().next(); assertEquals(first, fsm.getStateOfType(Object.class)); assertEquals(b, fsm.getStateOfType(StateB.class)); assertEquals(c, fsm.getStateOfType(StateC.class)); boolean fail = false; try { fsm.getStateOfType(Enum.class); } catch (final IllegalArgumentException e) { fail = true; } assertTrue(fail); }