Two Enums of the same type but with different value sets in Java? - enums

I am about to write a cli for my program. Now I want to have an enum for every possible command that contains a list of all available options for this command.
Each element of such "option" enums should store the fields identifier, helpText etc.
I don't want to code the definition of an option for every single enum.
I know that I can implement an enum like this:
public enum AddItemCommandOptions {
OPTION1("one", "infoText One"),
OPTION2("two", "infoText Two"),
OPTION3("three", "infoText Three");
private final String infoText;
private final String identifier;
AddCommandOption(String identifier, String infoText) {
this.identifier = identifier;
this.infoText = infoText;
}
public boolean identifiesWith(String identifier) {
return this.identifier.equals(identifier);
}
public String getInfoText() {
return this.infoText;
}
}
But can I do something like this so that I do not need to recode everything for a second enum:
public class CommandOption {
private final String infoText;
private final String identifier;
CommandOption(String identifier, String infoText) {
this.identifier = identifier;
this.infoText = infoText;
}
public boolean identifiesWith(String identifier) {
return this.identifier.equals(identifier);
}
public String getInfoText() {
return this.infoText;
}
}
public enum AddItemCommandOptions extends CommandOption{
OPTION1("one", "infoText One"),
OPTION2("two", "infoText Two"),
OPTION3("three", "infoText Three");
AddItemCommandOptions(String identifier, String infoText) {
super(identifier, infoText);
}
}
public enum RemoveItemCommandOptions extends CommandOption{
OPTION1("one", "infoText One"),
OPTION2("two", "infoText Two"),
OPTION3("three", "infoText Three");
RemoveItemCommandOptions(String identifier, String infoText) {
super(identifier, infoText);
}
}
I know that this approach doesn't work but is there a similar solution so that I don't have duplicated code?

Related

Return the built Enum to JSON

I have an object and an enum for it. When I give away an object, I want my enum inside the object to be displayed as an object with the name and value attributes without using DTO, or to be partially used. I want json to build this object itself (enum with name and value), and I give only the object in which this enum is contained.
public enum MyType {
TT("Time Tu"), TD("Time dust");
MyType(String value) {
this.value = value;
}
private String value;
public String getValue() {
return value;
}
#Override
public String toString() {
return value;
}
Here is the DTO, it may be necessary (get/set/constructor auto generated by Intellij Idea)
public class MyTypeWrapper {
private String name;
private String value;
}
#Entity
public class MyObject {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
private String number;
........
private MyType myType;
........
}
Perhaps serialization/deserialization is needed? How to do it?
It should go something like this:
{
.....
myType: {
"name: "TT",
"value: "TD"
},
.....
}
Perhaps this is a piece of the solution? But I'm not sure that it will work, and it's not clear how to serialize
public enum MyType {
......
#JsonValue
private MyTypeWrapper getWrapper()
return new MyTypeWrapper(this.name, this.value)
}
......
}
This turned out to be the solution
public enum MyType {
......
#JsonValue
private MyTypeWrapper getWrapper()
return new MyTypeWrapper(this.name, this.value)
}
......
}

Fix string contraints on JPA entity attribute

I am new in JPA,
I want to set only specific fix department names to attribute in entity as a fix string as constraints.I.e default values to attributes.
How to set it?
I think the best option is to use enumerated as indicated by Dinesh Dontha, try this:
Entity
#Entity
public class MyEntity implements Serializable(){
private MyEnum attribute;
}
Enum
public enum MyEnum {
NAME1("N1")
private String shortName;
private MyEnum(String shortName) {
this.shortName = shortName;
}
public String getShortName() {
return shortName;
}
public static MyEnum fromShortName(String shortName) {
switch (shortName) {
case "N1":
return NacionalidadEnum.NAME1;
default:
throw new IllegalArgumentException("ShortName [" + shortName
+ "] not supported.");
}
}
}
Converter
#Converter(autoApply = true)
public class MyEntityEnumConverter implements AttributeConverter<MyEnum, String> {
#Override
public String convertToDatabaseColumn(MyEnum myEnum) {
return myEnum.getShortName();
}
#Override
public MyEnum convertToEntityAttribute(String dbData) {
return MyEnum.fromShortName(dbData);
}
}

Add interfaces to groovy enums?

I am unable to add interfaces to groovy enums.
example:
interface DeviceType.groovy
public interface DeviceType{
public String getDevice()
}
enum Device.groovy
public enum Devices implements DeviceType {
PHONE{
public String getDevice(){
return "PHONE"
}
}, ALARM {
public String getDevice(){
return "ALARM"
}
}
}
Simple Test
public class MainTest(){
public static void main(String [] args) {
System.out.println(Devices.PHONE.getDevice());
//should print phone
}
}
This is pseudo code, but a pretty good example.
When I use it with Groovy, I get an error from IntelliJ that I need to make the interface abstract.
If I make it abstract, maven won't compile saying it can't be both static and final.
Any tips?
You need to define getDevice() in the enum. Then you can override it, like this:
enum Device.groovy
public enum Devices implements DeviceType {
PHONE{
public String getDevice(){
return "PHONE"
}
}, ALARM {
public String getDevice(){
return "ALARM"
}
};
public String getDevice(){
throw new UnsupportedOperationException();
}
}
Since an enum is a class, and your class is implementing the interface, it needs to implement the function. Right now what you have is an enum that's NOT implementing the function, whose instances are each subclasses that do have a function of the same name. But since the enum itself doesn't have it, that's not good enough.
I'd like to offer my preferred syntax for a situation such as this:
public enum Devices implements DeviceType {
PHONE("PHONE"), ALARM("ALARM")
private final String devName
public String getDevice() { return devName }
private Devices(devName) { this.devName = devName }
}
Or, if the "device" is always going to match the name of the enum instance, you might as well just return that:
public enum Devices implements DeviceType {
PHONE, ALARM
public String getDevice() { return name() }
}

Initialising Enum members using Spring

I have and Enum like below.
public enum MyEnum {
ENUM1("ENUM1Code", "ENUM1 Desc"), ENUM2("ENUM2Code", "ENUM2"), ENUM3("ENUM3Code", "ENUM3");
private String code;
private String description;
private MyEnum(String code, String description) {
this.code = code;
this.description = description;
}
public String getCode() {
return code;
}
public String getDescription() {
return description;
}
}
Can anybody suggest me how to remove the initialisation from this Enum and perform it through Spring ?
Thanks in advance
Dileep
You can't because enum are static objects.
You can externalize code/description and manage them manually.
EDIT:
I can't see need to use Spring for this type of jobs; you can achieve the same goal with easy code (a bit of Spring is used, the PropertiesLoaderUtils utility class).
Create a properties file where you store, for every enum, code and description and write utility code to read data; result of your custom code is a UDT like that:
class EnumWithData implements Serializable {
MyEnum enumValue;
String code;
String description;
// Write properties get/set
// Equals check for enumValue only
boolean equals(Object other) {
EnumWithData b = (EnumWithData)other;
return b.enumValue == this.enumValue;
}
}
abstract class EnumWithDataUtility {
private static Properties definition = PropertiesLoaderUtils.loadProperties("path/to/resource");
public final static EnumWithData getEnumWithData(MyEnum enumValue) {
EnumWithData udt = new EnumWithData();
udt.enumValue = enumValue;
...
return udt;
}
}

Playframework! Using #select for a Enum property

I'm trying to create a #select input for a enum field. Everything works fine until the form is submitted. It fails with a weird validation error -> "error.invalid"
here's my code
Enum class
package model;
...
public enum UserType {
UserType_Admin("Administrator"), UserType_Monitor("Monitor"), UserType_Audit("Audit");
private String desc;
private UserType(String desc) {
this.desc = desc;
}
#Override
public String toString() {
return Messages.get(desc);
}
public String getLabel() {
return toString();
}
public String getKey() {
return super.toString();
}
public static Map<String, String> options() {
LinkedHashMap<String, String> options = new LinkedHashMap<String, String>();
for (UserType ut : UserType.values()) {
Integer o = ut.ordinal();
options.put(o.toString(), ut.desc);
}
return options;
}
}
My Entity
#Entity
public class User extends Model {
...
#Id
public Long userID;
public UserType user_type;
}
Scala template
#form(routes.Users.save(userID)) {
#select(
userForm("user_type"),
options(model.UserType.options),
'_label -> Messages("UserType"), '_default -> Messages("choose_user_type"),
'_showConstraints -> true
)
}
on the controller the Save method:
public static Result save(Long userID) {
Form<User> userForm = form(User.class).bindFromRequest();
if (userForm.hasErrors()) { <- here it says that has errors
return badRequest(useredit.render(new Session(session()), userID,
userForm, new User()));
}
...
}
if I inspect the userForm variable, I get:
Form(of=class model.User, data={user_type=0}, value=None,
errors={user_type=[ValidationError(user_type,error.invalid,[])]})
The field user_type has the correct value, 0 if I choose the first item, 1 for the second, etc.
Screenshot
Anyone has a clue or a workaround for this? Maybe disable validation for this field? Tks guys

Resources