Fluent API with inheritance and generics

后端 未结 5 787
谎友^
谎友^ 2020-12-09 02:13

I\'m writing a fluent API to configure and instantiate a series of \"message\" objects. I have a hierarchy of message types.

To be able to access method of subclasse

5条回答
  •  感动是毒
    2020-12-09 02:39

    If you change the signatures like this you should neither get any warnings nor do you need any casts:

    abstract class Message> {
    
        public T withID(String id) {
            return self();
        }
    
        protected abstract T self();
    }
    
    abstract class CommandMessage> extends Message {
    
        public T withCommand(String command) {
            // do some work ...
            return self();
        }
    }
    
    class CommandWithParamsMessage extends CommandMessage {
    
        public static CommandWithParamsMessage newMessage() {
            return new CommandWithParamsMessage();
        }
    
        public CommandWithParamsMessage withParameter(String paramName, String paramValue) {
            // do some work ...
            return this;
        }
    
        @Override protected CommandWithParamsMessage self() {
            return this;
        }
    }
    

提交回复
热议问题