Java - SubType枚举或子类 [英] Java - SubType Enums or SubClass
问题描述
我试图将一个枚举
对应于一个类或返回该类,但我得到解决。如果我使用 CommandType.SELLSHARES
来返回 SellShares.class
,这种行为是否可行?或者我可以使用继承自父类型的不同类别来组织枚举?
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
for it to return SellShares.class
? Or can I organize the enums with different categories that inherit from the parent type?
命令 - ADMIN
, USER
,客户端
public enum CommandType {
// SELLSHARES, BUYSHARES, UPDATEUSER, ADDUSER, ADMINASSIGNMENT, BANUSER, CHANGESTATUS, REMOVEUSER
SELLSHARES (SellShares.class),
BUYSHARES (BuyShares.class);
private Class<Command> command;
CommandType(Class<Command> command) {
this.command = command;
}
private Class<Command> command() { return command; }
public static <T extends Enum<T>> T getInstance(final String value,
final Class<T> enumClass) {
return Enum.valueOf(enumClass, value);
}
}
或
public enum CommandType {
AdminCommands,
UserCommands
}
enum AdminCommands {
UPDATEUSER,
ADDUSER,
ADMINASSIGNMENT,
BANUSER,
CHANGESTATUS,
REMOVEUSER
}
enum User {
SELLSHARES,
BUYSHARES
}
有问题 getByType
void initialCommands() throws Exception
{
listCommands = Commands.getByType(Commands.Type.ADMIN);
for (Commands command : listCommands)
{
Command commandss = command.newInstance();
//addCommand(command.getCommand());
//log.trace(command.newInstance());
}
}
推荐答案
你必须寻找这样的东西:
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.
这篇关于Java - SubType枚举或子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!