Java - SubType Enums or SubClass

前端 未结 1 1780
谎友^
谎友^ 2021-01-21 07:00

I\'m trying to have an enum correspond to a class or return that class but I get to resolve. Is this behavior possible if I use the CommandType.SELLSHARES

相关标签:
1条回答
  • 2021-01-21 07:38

    You must be looking for something like this:

    public enum Commands {
    
        UPDATE_USER(Type.ADMIN, UpdateUser.class),
        ADD_USER(Type.ADMIN, AddUser.class),
        ADMIN_ASSIGNMENT(Type.ADMIN, AdminAssignment.class),
        BAN_USER(Type.ADMIN, BanUser.class),
        CHANGE_STATUS(Type.ADMIN, ChangeStatus.class),
        REMOVE_USER(Type.ADMIN, RemoveUser.class),
    
        SELL_SHARES(Type.USER, SellShares.class),
        BUY_SHARES(Type.USER, BuyShares.class);
    
        public enum Type {
            ADMIN,
            USER;
        }
    
        public static List<Commands> getByType(Type type) {
            List<Commands> commands = new ArrayList<Commands>();
            for (Commands command : values()) {
                if (command.type.equals(type)) {
                    commands.add(command);
                }
            }
            return commands;
        }
    
        private final Type type;
    
        private final Class<? extends Command> command;
    
        private Commands(Type type, Class<? extends Command> command) {
            this.type = type;
            this.command = command;
        }
    
        public Class<? extends Command> getCommand() {
            return command;
        }
    
        public Command newInstance() throws Exception {
            return command.newInstance();
        }
    
    }
    

    To create an instance, simply use:

    Commands.UPDATE_USER.newInstance();
    

    To get all the commands for a given type:

    Commands.getByType(Commands.Type.ADMIN);
    

    Note that using this method, the Commands subclasses must implement a public nullary constructor.

    0 讨论(0)
提交回复
热议问题