简体   繁体   English

为JAVA中的列表定义此枚举的构造函数?

[英]Define constructor for this enum for the list in JAVA?

public enum Role{ 
    ADMIN("SMITH","KEVIN"),
    STUDENT("JACK", "JILL", "MARRY", "MALA"),
    GURDIAN("BOB");
}

How can I define constructor for this enum in JAVA? 如何在JAVA中为此枚举定义构造函数?

Can I initiate as follows? 我可以按以下方式发起吗?

Role(List<String> userlist){}

The most suitable constructor I can think of is with a String varargs, as follows: 我能想到的最合适的构造函数是String varargs,如下所示:

Role(String... names) {
    // TODO
}

A constructor taking List<String> will not match the signature and will not compile on its own. 采用List<String>构造函数将不匹配签名,也不会自行编译。

You can always overload the constructors though. 但是,您始终可以重载构造函数。

You definitely go with the varargs style constructor 您绝对可以使用varargs样式构造函数

private final List<String> values;
Role(String... values) {
  this.values = Arrays.asList(values);
} 

public List<String> getValues() {
    return values;
}

And then when you need the particular role based on the provided names go for the find as 然后,当您需要基于提供的名称的特定角色时,请查找为

public static Role find(String name) {
for (Role role: Role.values()) {
    if (rol.getValues().contains(name)) {
        return rol;
    }
}
return null;

} }

public enum Role{ 
    ADMIN("SMITH","KEVIN"),
    STUDENT("JACK", "JILL", "MARRY", "MALA"),
    GURDIAN("BOB");

    private String[] values;

    Role(String ... values) {
         this.values = values;
    }
}

You can use use variable arguments varargs in constructor like: 您可以在构造函数中使用use变量参数varargs,例如:

public enum Role {

    ADMIN("SMITH","KEVIN"),
    STUDENT("JACK", "JILL", "MARRY", "MALA"),
    GURDIAN("BOB");

    private Role(String...name) {
        this.values = name;
    }
}

There is declaration (in enum), storage in field, and usage. 有声明(在枚举中),在字段中存储和用法。

As these are singletons, defined in the enum class, the form of the declaration is only important with respect to elegance. 由于这些是枚举类中定义的单例,因此声明的形式仅在优雅方面很重要。

public enum Role{ 
    ADMIN(user("SMITH", "KEVIN")),
    STUDENT(user("JACK", "JILL"), user("MARRY", "MALA")),
    GURDIAN(user("BOB"));

    // Local factory methods
    // User or Principal
    private User user(String firstname, String surname) { ... }
    private User user(String firstname) { ---}

    private final Set<User> users;

    Role(User... users) {
        if (users.length == 1) { ...
        }
        this.users = new HashSet<>();
        Collections.addAll(users);
    }

    public boolean ...(...) {
        ...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM