Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 334337
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T10:02:41+00:00 2026-05-12T10:02:41+00:00

i made a state machine and would like it to take advantage of generics

  • 0

i made a state machine and would like it to take advantage of generics in java. currently i dont see the way i can make this work and get pretty looking code. im sure this design problem has been approached many times before, and im looking for some input. heres a rough outline.

class State { ... }

only one copy of each distinct state object (mostly anonymous classes tied to static final variables), it has custom data for each state. each state object has a state parent (there is one root state)

class Message { ... } 

each message is created separately and each one has custom data. they may subclass each other. there is one root message class.

class Handler { ... } 

each handler is created only once and deals with a specific state / message combo.

class StateMachine { ... }

currently keeps track of the current state, and a list of all (State,Message) -> Handler mappings. it has other functionality as well. i am trying to keep this class generic and subclass it with type parameters as its used a bunch of times in my program, and each time with a different set of Message‘s / State‘s / and Handler‘s. different StateMachine‘s will have different parameters to their handlers.

Approach A

have the state machine keep track of all mappings.

class StateMachine<MH extends MessageHandler> {
  static class Delivery {
    final State state;
    final Class<? extends Message> msg;
  }
  HashMap<Delivery, MH> delegateTable;
  ...
}

class ServerStateMachine extends StateMachine<ServerMessageHandler> {
  ...
}

allows me to have custom handler methods for this particular state machine. the parameters for the handler.process method can be overwritten. However, the handler cannot be parameterized by the message type.

Problem: this involves using the instanceof sanity check for each message handler (making sure it is getting the message it is expecting).

Approach B

lets make each message handler parameterized by message type

class MessageHandler<M extends Message> {
  void process(M msg) { .... }
}

Problem: type erasure will prevent me from storing these in a nice hashmap since all the MessageHandler‘s will be typed differently. if i can store them in a map, i wont be able to retreive them and call them with the proper arguements.

Approach C

have the state object handle all messages.

class State<M extends Message> { ... }
class ServerState<M extends ServerMessage> extends State<M> { ... }

i have message handlers tied to specific state machine states (by putting them inside), (each instance of a state machine would have its own list of valid states), which allows the handlers to be of a specific type. (server state machine -> server message handler).

Problem: each state can only handle one message type. you also lose the idea that parent state’s can handle different messages than child states. type erasure also prevents the StateMachine from calling current states process methods.

Approach D

have the message’s process themselves based on state.

Problem: never really considered, since each message should have a different handler based on the current state machine state. the sender will not know the current StateMachine‘s state.

Approach E

forget about generics and hard code state / message handling with a switch statement.

Problem: sanity

Unsafe Solution:

Thanks for your input everybody, i think the problem was i did not reduce this to good problem (too much discussion) heres what i have now.

public class State { }

public class Message { }

public class MessageHandler<T extends Message> { }

public class Delivery<T extends Message> {
  final State state;
  final Class<T> msgClass;
}

public class Container {

  HashMap<Delivery<? extends Message>, MessageHandler<? extends Message>> table;

  public <T extends Message> add(State state, Class<T> msgClass, MessageHandler<T> handler) {
    table.put(new Delivery<T>(state, msgClass), handler);
  }

  public <T extends Message> MessageHandler<T> get(State state, T msg) {
    // UNSAFE - i cannot cast this properly, but the hashmap should be good
    MessageHandler<T> handler = (MessageHandler<T>)table.get(new Delivery<T>(state, msg.getClass()));
    return handler;
  }

}
  • 1 1 Answer
  • 1 View
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T10:02:41+00:00Added an answer on May 12, 2026 at 10:02 am

    For approach B, don’t use a “nice” hashmap. Instead, write a heterogenous typesafe container mapping handlers to Class objects:

    interface Handler<T extends Message> {
    ...}
    
    
    interface Message {...}
    
    interface HandlerContainer {
    
        <T extends Message> void register(Class<T> clazz, Handler<T> handler);
    
        <T extends Message> Handler<T> getHandler(T t);
    
    }
    
    
    class HandlerContainerImpl implements HandlerContainer {
    
        private final Map<Class<?>,Handler<?>> handlers = new HashMap<Class<?>,Handler<?>>();
    
        <T extends Message> void register(Class<T> clazz, Handler<T> handler) {
              if (clazz==null || handler==null) {
                 throw new IllegalArgumentException();
              }
              handlers.put(clazz,handler);
        }
    
        //Type safety is assured by the register message and generic bounds
        @SuppressWarnings("unchecked")
        <T extends Message> Handler<T> getHandler(T t) {
                return  (Handler<T>)handlers.get(t.getClass());
    
        }
    
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I would like to use the OnWorkflowItemChanged event in a WSS 3.0 State machine
I've made a UIPanRecognizer like this. - (void)pan:(UIPanGestureRecognizer *)gesture { if ((gesture.state == UIGestureRecognizerStateChanged)
Miro Samek's QM graphical modeling tool (http://www.state-machine.com/qm/) seems like a good tool for semi
I've just made a really simple toggle button. Function checks the state (a class),
I have a state machine with one state which dispatches some message (e.g. text)
I want to implement the GUI as a state machine. I think there are
I am working a project where i need to create a state machine work
First, I would like to mention that I also had this problem when 2.2
No connection could be made because the target machine actively refused it 127.0.0.1:25 Description:
I have made a LinkedList to store State objects which is a class I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.