Use enum like a getter? - java

I have a util class that keeps track of important system variables:
public static final String REQUEST_ADDRESS = "http.request.address";
public static final String REQUEST_PORT = "http.request.port";
public static final String get(String property) {
return System.getProperty(property);
}
And I can retrieve these values like so:
String port = SystemPropertyHelper.get(SystemPropertyHelper.REQUEST_PORT);
Is it possible, in Java, to get these like an enum?
REQUEST_PORT {
return System.getProperty("http.request.port");
}
String port = SystemPropertyHelper.REQUEST_PORT;

I'd solve it that way.
public static final String REQUEST_PORT = System.getProperty("http.request.port");

enum SystemPropertyHelper {
REQUEST_PORT("http.request.port"), ...;
private String key;
Config(String key) {
this.key = key;
}
public String get() {
return System.getProperty(key);
}
}
and use it like SystemPropertyHelper.REQUEST_PORT.get();

Sure, you could create an enum like this, which would give you access to the property name, and the value:
public enum SystemPropertyEnum {
REQUEST_PORT("http.request.port"),
REQUEST_ADDRESS("http.request.address");
private String propertyName;
private String value;
SystemPropertyEnum(final String propertyName) {
this.propertyName = propertyName;
this.value = System.getProperty(propertyName);
}
public String getPropertyName() {
return propertyName;
}
public String getValue() {
return value;
}
}
However, you could avoid the need to call a getter by just using public static final String variables for your properties, as #halloei suggests.

Also you can do something like this:
public enum Properties {
REQUEST_PORT("http.request.port"),
REQUEST_USE_SSL("http.request.ssl");
// Add others...
private final String value;
Properties(String value) {
this.value = System.getProperty(value);
}
public String getValue() {
return this.value;
}
}
This can be use like:
String port = Properties.REQUEST_PORT.getValue();

Related

Returning an empty string if the enum constant is not found

Suppose I have an enum class of
public enum ValueType {
time("15"),
post("15"),
comment("F"),
private final String valueType;
ValueType(final String valueType) {
this.valueType = valueType;
};
public String getValueType() {
return this.valueType;
}
}
and Im getting the constant value using
ValueType.valueOf(dynamicValueString).getValueType()
Supposed there is no enum constant for that dynamicValueString.
How can I set the value to an empty string if the enum is not found? without using try catch?
I'd argue that you are right to avoid exceptions for normal program flow. Anyway, I use a map as suggested in comment:
public enum TestType {
ONE("1"),
TWO("2"),
THREE("3");
private final String str;
TestType(String str) {
this.str = str;
}
private static final Map<String, TestType> MAP = Arrays.stream(values())
.collect(Collectors.toMap(TestType::name, Function.identity()));
public static String typeByName(String name) {
TestType type = MAP.get(name);
return type == null ? "" : type.str;
}
}
public enum ValueType {
time("15"),
post("15"),
comment("F");
private final String valueType;
ValueType(final String valueType) {
this.valueType = valueType;
}
public String getValueType() {
return this.valueType;
}
public static String getValueType(String name) {
return Arrays.stream(ValueType.values())
.filter(v -> name.equalsIgnoreCase(v.valueType))
.findFirst()
.map(v -> v.valueType)
.orElse("");
}
}
You need to implement a custom lookup on your enum:
public enum ValueType {
//...
public static String lookupValueType(String constant) {
try {
return ValueType.valueOf(constant).valueType;
} catch (IllegalArgumentException e) {
return "";
}
}
}
And just use ValueType.lookupValueType(dynamicValueString) (I'm assuming dynamicValueString is meant to match enum value names)

how to convert "value" to enum?

I have this enum class:
public enum IconImageTag {
None("val1"),
USD("val2"),
EURO("val3");
}
given a string which represent a "value" (say `"val"1)
how can I convert it to the corresponding enum?
update
I have tried this. Why is this illegal to access static member from the ctor? I get an error.
private final String value;
private static final Map<String, IconImageTag> stringToEnumMap = new HashMap<>();
IconImageTag(String value) {
this.value = value;
stringToEnumMap.put(value, this);
}
Ideally, you'd build up a Map<String, IconImageTag> and add an appropriate method. For example:
public enum IconImageTag {
NONE("val1"),
USD("val2"),
EURO("val3");
private final String value;
private final Map<String, IconImageTag> valueMap = new HashMap<>();
static {
for (IconImageTag tag : values()) {
valueMap.put(tag.value, tag);
}
}
private IconImageTag(String value) {
this.value = value;
}
public static IconImageTag fromValue(String value) {
return valueMap.get(value);
}
}
(I'd probably use a different term from "value" here, to avoid confusion with valueOf() etc...)
Note the use of the static initializer block - any static variables in an enum are initialized after the enum values themselves, which means that when the enum constructor runs, valueMap will still be null.
You can also iterate over every enum.
public enum IconImageTag {
None("val1"),
USD("val2"),
EURO("val3");
private final String value;
private IconImageTag(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public static IconImageTag getByValue(String value) {
for(IconImageTag iconImageTag : values()) {
if(iconImageTag.getValue().equals(value)) {
return iconImageTag;
}
}
return null;
}

How to create Enum for the given objects

I have a class called - SparqlResource.java and in the class I am instantiating four objects like this-
public static final SparqlResource MARK_SIMPLE_TYPE = new SparqlResource("ldmext/MarkSimpleType.rq");
public static final SparqlResource FORTRESS_HAS_ENVOY = new SparqlResource("ldmext/FortressHasEnvoy.rq");
public static final SparqlResource FORTRESS_HAS_GUARD = new SparqlResource("ldmext/FortressHasGuard.rq");
public static final SparqlResource FORTRESS_HAS_PORT = new SparqlResource("ldmext/FortressHasPort.rq");
Now from another class - JenaLanguageConstructor.java, I am referencing these objects like this-
runOneQuery(SparqlResource.MARK_SIMPLE_TYPE, true);
runOneQuery(SparqlResource.FORTRESS_HAS_ENVOY, true);
runOneQuery(SparqlResource.FORTRESS_HAS_GUARD, true);
runOneQuery(SparqlResource.FORTRESS_HAS_PORT, true);
Now my question is is there any way I can use enums to achieve this, if so then can any one please give me a sample code which I can use to create the enum?
public enum SPARQLENUM {
MARK_SIMPLE_TYPE("ldmext/MarkSimpleType.rq") ,
FORTRESS_HAS_ENVOY("ldmext/FortressHasEnvoy.rq") ,
FORTRESS_HAS_GUARD("ldmext/FortressHasGuard.rq") ,
FORTRESS_HAS_PORT("ldmext/FortressHasPort.rq");
private String value;
private SPARQLENUM(String value) {
this.value = value;
}
public String getValue(){
return value;
}
}
And you can call it this way:
SPARQLENUM.FORTRESS_HAS_ENVOY.getValue()
EDITED
If you need the SparqlResource object, you can create the enum this way:
public enum SPARQLENUM {
MARK_SIMPLE_TYPE(new SparqlResource("ldmext/MarkSimpleType.rq")) ,
FORTRESS_HAS_ENVOY(new SparqlResource("ldmext/FortressHasEnvoy.rq")) ,
FORTRESS_HAS_GUARD(new SparqlResource("ldmext/FortressHasGuard.rq")) ,
FORTRESS_HAS_PORT(new SparqlResource("ldmext/FortressHasPort.rq"));
private SparqlResource value;
private SPARQLENUM(SparqlResource value) {
this.value = value;
}
public SparqlResource getValue(){
return value;
}
}
Well, creating an enum wouldn't be that hard:
enum MyEnum {
VALUE1("name 1"),
VALUE2("name 2");
private String name;
private MyEnum(String n) {
name = n;
}
//whatever else you need
}

How can I declare enums using java

I want to convert this sample C# code into a java code:
public enum myEnum {
ONE = "one",
TWO = "two",
};
Because I want to change this constant class into enum
public final class TestConstants {
public static String ONE = "one";
public static String TWO= "two";
}
public enum MyEnum {
ONE(1),
TWO(2);
private int value;
private MyEnum(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
In short - you can define any number of parameters for the enum as long as you provide constructor arguments (and set the values to the respective fields)
As Scott noted - the official enum documentation gives you the answer. Always start from the official documentation of language features and constructs.
Update: For strings the only difference is that your constructor argument is String, and you declare enums with TEST("test")
enums are classes in Java. They have an implicit ordinal value, starting at 0. If you want to store an additional field, then you do it like for any other class:
public enum MyEnum {
ONE(1),
TWO(2);
private final int value;
private MyEnum(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
}
Quite simply as follows:
/**
* #author The Elite Gentleman
*
*/
public enum MyEnum {
ONE("one"), TWO("two")
;
private final String value;
private MyEnum(final String value) {
this.value = value;
}
public String getValue() {
return value;
}
#Override
public String toString() {
// TODO Auto-generated method stub
return getValue();
}
}
For more info, visit Enum Types from Oracle Java Tutorials. Also, bear in mind that enums have private constructor.
Update, since you've updated your post, I've changed my value from an int to a String.
Related: Java String enum.
Well, in java, you can also create a parameterized enum. Say you want to create a className enum, in which you need to store classCode as well as className, you can do that like this:
public enum ClassEnum {
ONE(1, "One"),
TWO(2, "Two"),
THREE(3, "Three"),
FOUR(4, "Four"),
FIVE(5, "Five")
;
private int code;
private String name;
private ClassEnum(int code, String name) {
this.code = code;
this.name = name;
}
public int getCode() {
return code;
}
public String getName() {
return name;
}
}
public enum MyEnum
{
ONE(1),
TWO(2);
private int value;
private MyEnum(int val){
value = val;
}
public int getValue(){
return value;
}
}
public enum NewEnum {
ONE("test"),
TWO("test");
private String s;
private NewEnum(String s) {
this.s = s);
}
public String getS() {
return this.s;
}
}

Using Enum values as String literals

What is the best way to use the values stored in an Enum as String literals?
For example:
public enum Modes {
some-really-long-string,
mode1,
mode2,
mode3
}
Then later I could use Mode.mode1 to return its string representation as mode1. Without having to keep calling Mode.mode1.toString().
You can't. I think you have FOUR options here. All four offer a solution but with a slightly different approach...
Option One: use the built-in name() on an enum. This is perfectly fine if you don't need any special naming format.
String name = Modes.mode1.name(); // Returns the name of this enum constant, exactly as declared in its enum declaration.
Option Two: add overriding properties to your enums if you want more control
public enum Modes {
mode1 ("Fancy Mode 1"),
mode2 ("Fancy Mode 2"),
mode3 ("Fancy Mode 3");
private final String name;
private Modes(String s) {
name = s;
}
public boolean equalsName(String otherName) {
// (otherName == null) check is not needed because name.equals(null) returns false
return name.equals(otherName);
}
public String toString() {
return this.name;
}
}
Option Three: use static finals instead of enums:
public final class Modes {
public static final String MODE_1 = "Fancy Mode 1";
public static final String MODE_2 = "Fancy Mode 2";
public static final String MODE_3 = "Fancy Mode 3";
private Modes() { }
}
Option Four: interfaces have every field public, static and final:
public interface Modes {
String MODE_1 = "Fancy Mode 1";
String MODE_2 = "Fancy Mode 2";
String MODE_3 = "Fancy Mode 3";
}
Every enum has both a name() and a valueOf(String) method. The former returns the string name of the enum, and the latter gives the enum value whose name is the string. Is this like what you're looking for?
String name = Modes.mode1.name();
Modes mode = Modes.valueOf(name);
There's also a static valueOf(Class, String) on Enum itself, so you could also use:
Modes mode = Enum.valueOf(Modes.class, name);
You could override the toString() method for each enum value.
Example:
public enum Country {
DE {
#Override
public String toString() {
return "Germany";
}
},
IT {
#Override
public String toString() {
return "Italy";
}
},
US {
#Override
public String toString() {
return "United States";
}
}
}
Usage:
public static void main(String[] args) {
System.out.println(Country.DE); // Germany
System.out.println(Country.IT); // Italy
System.out.println(Country.US); // United States
}
As Benny Neugebauer mentions, you could overwrite the toString(). However instead overwriting the toString for each enum field I like more something like this:
public enum Country{
SPAIN("EspaƱa"),
ITALY("Italia"),
PORTUGAL("Portugal");
private String value;
Country(final String value) {
this.value = value;
}
public String getValue() {
return value;
}
#Override
public String toString() {
return this.getValue();
}
}
You could also add a static method to retrieve all the fields, to print them all, etc.
Simply call getValue to obtain the string associated to each Enum item
mode1.name() or String.valueOf(mode1). It doesn't get better than that, I'm afraid
public enum Modes {
MODE1("Mode1"),
MODE2("Mode2"),
MODE3("Mode3");
private String value;
public String getValue() {
return value;
}
private Modes(String value) {
this.value = value;
}
}
you can make a call like below wherever you want to get the value as a string from the enum.
Modes.MODE1.getvalue();
This will return "Mode1" as a String.
For my enums I don't really like to think of them being allocated with 1 String each. This is how I implement a toString() method on enums.
enum Animal
{
DOG, CAT, BIRD;
public String toString(){
switch (this) {
case DOG: return "Dog";
case CAT: return "Cat";
case BIRD: return "Bird";
}
return null;
}
}
You can use Mode.mode1.name() however you often don't need to do this.
Mode mode =
System.out.println("The mode is "+mode);
As far as I know, the only way to get the name would be
Mode.mode1.name();
If you really need it this way, however, you could do:
public enum Modes {
mode1 ("Mode1"),
mode2 ("Mode2"),
mode3 ("Mode3");
private String name;
private Modes(String s) {
name = s;
}
}
my solution for your problem!
import java.util.HashMap;
import java.util.Map;
public enum MapEnumSample {
Mustang("One of the fastest cars in the world!"),
Mercedes("One of the most beautiful cars in the world!"),
Ferrari("Ferrari or Mercedes, which one is the best?");
private final String description;
private static Map<String, String> enumMap;
private MapEnumSample(String description) {
this.description = description;
}
public String getEnumValue() {
return description;
}
public static String getEnumKey(String name) {
if (enumMap == null) {
initializeMap();
}
return enumMap.get(name);
}
private static Map<String, String> initializeMap() {
enumMap = new HashMap<String, String>();
for (MapEnumSample access : MapEnumSample.values()) {
enumMap.put(access.getEnumValue(), access.toString());
}
return enumMap;
}
public static void main(String[] args) {
// getting value from Description
System.out.println(MapEnumSample.getEnumKey("One of the fastest cars in the world!"));
// getting value from Constant
System.out.println(MapEnumSample.Mustang.getEnumValue());
System.out.println(MapEnumSample.getEnumKey("One of the most beautiful cars in the world!"));
System.out.println(MapEnumSample.Mercedes.getEnumValue());
// doesnt exist in Enum
System.out.println("Mustang or Mercedes, which one is the best?");
System.out.println(MapEnumSample.getEnumKey("Mustang or Mercedes, which one is the best?") == null ? "I don't know!" : "I believe that "
+ MapEnumSample.getEnumKey("Ferrari or Mustang, which one is the best?") + " is the best!.");
// exists in Enum
System.out.println("Ferrari or Mercedes, wich one is the best?");
System.out.println(MapEnumSample.getEnumKey("Ferrari or Mercedes, which one is the best?") == null ? "I don't know!" : "I believe that "
+ MapEnumSample.getEnumKey("Ferrari or Mercedes, which one is the best?") + " is the best!");
}
}
You can simply use:
""+ Modes.mode1
public enum Environment
{
PROD("https://prod.domain.com:1088/"),
SIT("https://sit.domain.com:2019/"),
CIT("https://cit.domain.com:8080/"),
DEV("https://dev.domain.com:21323/");
private String url;
Environment(String envUrl) {
this.url = envUrl;
}
public String getUrl() {
return url;
}
}
String prodUrl = Environment.PROD.getUrl();
It will print:
https://prod.domain.com:1088/
This design for enum string constants works in most of the cases.
Enum is just a little bit special class. Enums can store additional fields, implement methods etc. For example
public enum Modes {
mode1('a'),
mode2('b'),
mode3('c'),
;
char c;
private Modes(char c) {
this.c = c;
}
public char character() {
return c;
}
}
Now you can say:
System.out.println(Modes.mode1.character())
and see output:
a
package com.common.test;
public enum Days {
monday(1,"Monday"),tuesday(2,"Tuesday"),wednesday(3,"Wednesday"),
thrusday(4,"Thrusday"),friday(5,"Friday"),saturday(6,"Saturday"),sunday(7,"Sunday");
private int id;
private String desc;
Days(int id,String desc){
this.id=id;
this.desc=desc;
}
public static String getDay(int id){
for (Days day : Days.values()) {
if (day.getId() == id) {
return day.getDesc();
}
}
return null;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
};
This method should work with any enum:
public enum MyEnum {
VALUE1,
VALUE2,
VALUE3;
public int getValue() {
return this.ordinal();
}
public static DataType forValue(int value) {
return values()[value];
}
public String toString() {
return forValue(getValue()).name();
}
}
i found this one is more easy for preventing type error:
public enum Modes {
some-really-long-string,
mode1,
mode2,
mode3;
String str;
Modes(){
this.str = super.name();
}
#Override
#NonNull
public String toString() {
return str;
}
however - this may work when you need to use a String on a log/println or whenever java compiles the toString() method automatically, but on a code line like this ->
// sample method that require (string,value)
intent.putExtra(Modes.mode1 ,shareElement.getMode()); // java error
// first argument enum does not return value
instead as mentioned above you will still have to extend the enum and use .name() in those cases like this:
intent.putExtra(Modes.mode1.name() ,shareElement.getMode());
after many tries I have come with this solution
public static enum Operation {
Addition, Subtraction, Multiplication, Division,;
public String getUserFriendlyString() {
if (this==Addition) {
return " + ";
} else if (this==Subtraction) {
return " - ";
} else if (this==Multiplication) {
return " * ";
} else if (this==Division) {
return " / ";
}
return "undefined";
}
}
You can try this:
public enum Modes {
some-really-long-string,
mode1,
mode2,
mode3;
public String toString(){
switch(this) {
case some-really-long-string:
return "some-really-long-string";
case mode2:
return "mode2";
default: return "undefined";
}
}
}
use mode1.name() or String.valueOf(Modes.mode1)

Categories

Resources