Using enums in Java - java

Constants given in the following enum,
enum StringConstatns {
ONE {
#Override
public String toString() {
return "One";
}
},
TWO {
#Override
public String toString() {
return "Two";
}
}
}
public final class Main {
public static void main(String... args) {
System.out.println(StringConstatns.ONE + " : " + StringConstatns.TWO);
}
}
can be accessed just like StringConstatns.ONE and StringConstatns.TWO as shown in the main() method.
I have the following enum representing an int constant(s).
public enum IntegerConstants
{
MAX_PAGE_SIZE(50);
private final int value;
private IntegerConstants(int con) {
this.value = con;
}
public int getValue() {
return value;
}
}
This requires accessing the constant value like IntegerConstants.MAX_PAGE_SIZE.getValue().
Can this enum be modified somehow in a way that value can be accessed just like IntegerConstants.MAX_PAGE_SIZE as shown in the first case?

The answer is no, you cannot. You have to call:
IntegerConstants.MAX_PAGE_SIZE.getValue()
If you really want a shortcut, you could define a constant somewhere like this:
public class RealConstants {
final public static int MAX_PAGE_SIZE = 50;
}
public enum IntegerConstants
{
MAX_PAGE_SIZE(RealConstants.MAX_PAGE_SIZE);//reuse the constant
private final int value;
private IntegerConstants(int con) {
this.value = con;
}
public int getValue() {
return value;
}
}

This is not going to work because your first example does implicit calls to .toString() when you concatenate them with +, whereas there is no implicit conversion to int which is needed for your second example.
You could define them as static final fields, this does exactly what you are searching for:
public class IntegerConstants {
public static final int MAX_PAGE_SIZE = 50;
}

Related

How can I add customer methods to ENUM to get string value of the value I am using (if needed) [duplicate]

I have a enum defined like this and I would like to be able to obtain the strings for the individual statuses. How should I write such a method?
I can get the int values of the statuses but would like the option of getting the string values from the ints as well.
public enum Status {
PAUSE(0),
START(1),
STOP(2);
private final int value;
private Status(int value) {
this.value = value
}
public int getValue() {
return value;
}
}
if status is of type Status enum, status.name() will give you its defined name.
You can use values() method:
For instance Status.values()[0] will return PAUSE in your case, if you print it, toString() will be called and "PAUSE" will be printed.
Use default method name() as given bellows
public enum Category {
ONE("one"),
TWO ("two"),
THREE("three");
private final String name;
Category(String s) {
name = s;
}
}
public class Main {
public static void main(String[] args) throws Exception {
System.out.println(Category.ONE.name());
}
}
You can add this method to your Status enum:
public static String getStringValueFromInt(int i) {
for (Status status : Status.values()) {
if (status.getValue() == i) {
return status.toString();
}
}
// throw an IllegalArgumentException or return null
throw new IllegalArgumentException("the given number doesn't match any Status.");
}
public static void main(String[] args) {
System.out.println(Status.getStringValueFromInt(1)); // OUTPUT: START
}
I believe enum have a .name() in its API, pretty simple to use like this example:
private int security;
public String security(){ return Security.values()[security].name(); }
public void setSecurity(int security){ this.security = security; }
private enum Security {
low,
high
}
With this you can simply call
yourObject.security()
and it returns high/low as String, in this example
You can use custom values() method:
public enum SortType
{
Scored, Lasted;
public int value(){
return this == Lasted ? 1:0;
}
}

Returning a string literal from an Enum

I'm trying to use an Enum to set a finite list of possible distances, with the string being used as a cssSelector within a Selenium API method:
public enum DistanceFrom {
FIVEMILES("a[data-reactid='.2cr8yg16ohc.2.1.0.2:$5.0']"),
TENMILES("a['.2cr8yg16ohc.2.1.0.2:$10.0.2']"),
TWENTYMILES("a['.2cr8yg16ohc.2.1.0.2:$20.0']"),
THIRTYMILES("a['.2cr8yg16ohc.2.1.0.2:$30.0']");
private String value;
DistanceFrom(String value){
this.value=value;
}
#Override
public String toString(){
return value;
}
}
I use this in a test:
local.setDistance(DistanceFrom.FIVEMILES.toString());
In which setDistance is a fluent method within a page object:
public LocalNewsPage setDistance(String value) {
WebElement setDistanceButton = driver.findElement(By.cssSelector(value));
setDistanceButton.click();
return this;
}
Why must I declare:
local.setDistance(DistanceFrom.FIVEMILES.toString());
And not be able to simply:
local.setDistance(DistanceFrom.FIVEMILES);
If you can edit the setDistance method, you can change it to accept a DistanceFrom:
public LocalNewsPage setDistance(DistanceFrom value) {
WebElement setDistanceButton = driver.findElement(By.cssSelector(value.toString()));
setDistanceButton.click();
return this;
}
Alternatively, you can change the enum values in DistanceFrom to static final Strings:
public final class DistanceFrom {
public static final String FIVEMILES = "a[data-reactid='.2cr8yg16ohc.2.1.0.2:$5.0']";
public static final String TENMILES = "a['.2cr8yg16ohc.2.1.0.2:$10.0.2']";
public static final String TWENTYMILES = "a['.2cr8yg16ohc.2.1.0.2:$20.0']";
public static final String THIRTYMILES = "a['.2cr8yg16ohc.2.1.0.2:$30.0']";
private DistanceFrom() {}
}

How to retrieve a constant value by providing a string?

Considering this class
package com.bluegrass.core;
public class Constants {
public static final String AUTHOR="bossman";
public static final String COMPANY="Bluegrass";
//and many more constants below
}
I want to create a function that goes like this:
getConstantValue("AUTHOR") //this would return "bossman"
Any ideas how this can be done?
You can use reflection:
public static String getConstantValue(String name) {
try {
return (String) Constants.class.getDeclaredField(name).get(null);
} catch (Exception e) {
throw new IllegalArgumentException("Constant value not found: " + name, e);
}
}
UPDATE: Enum solution.
If you can change the Constants class to be an enum, it would be like this instead:
private static String getConstantValue(String name) {
return Constants.valueOf(name).getText();
}
But that requires something like this for Constants:
public enum Constants {
AUTHOR("bossman"),
COMPANY("Bluegrass");
private final String text;
private Constants(String text) {
this.text = text;
}
public String getText() {
return this.text;
}
}
Probably the simplest solution (and also work with enums instead of String is typesafe) is to work with enum, provided you are able to change the public static final fields into an enum.
public enum Constants {
AUTHOR("bossman"),
COMPANY("Bluegrass");
private final String content;
Constants (String content) {
this.content= content;
}
public String getContent() {
return content;
}
public static Constants getConstant(String content) {
for (Constants constant : Constants.values()) {
if (constant.getContent().equals(content)) {
return constant;
}
}
return null; //default value
}
}
Usage:
Constants.valueOf("AUTHOR") == Constants.AUTHOR
Constants.getConstant("bossman") == Constants.AUTHOR
Constants.AUTHOR.getContent() == "bossman"
So instead of OP's getConstantValue("AUTHOR") it would be Constants.valueOf("AUTHOR").getContent()
There is a multitude of methods to solve this.
One way is to use a switch.
Example:
public String foo(String key) throws AnException {
switch (key) {
case case1:
return constString1;
case case2:
return constString2;
case case3:
return constString3;
...
default:
throws NotValidKeyException; //or something along these lines
}
}
The other method is to create a map<string,string> and fill it with the desired key,pairs.

How to use constructor in enum?

I want to use an enum to create a singleton class in java. Should look like this:
public enum mySingleton implements myInterface {
INSTANCE;
private final myObject myString;
private mySingleton(myObject myString) {
this.myString= myString;
}
}
Looks like I cannot use any parameters in the constructor. Is there any workaround for this? Thanks in advance
Yor enum is wrong. Below correct declaration:
public class Hello {
public enum MyEnum {
ONE("One value"), TWO("Two value"); //Here elements of enum.
private String value;
private MyEnum(String value) {
this.value = value;
System.out.println(this.value);
}
public String getValue() {
return value;
}
}
public static void main(String[] args) {
MyEnum e = MyEnum.ONE;
}
}
Output:
One value
Two value
Conctructor is invoked for each element of enum.
You can try this:
enum Car {
lamborghini(900),tata(2),audi(50),fiat(15),honda(12);
private int price;
Car(int p) {
price = p;
}
int getPrice() {
return price;
}
}
public class Main {
public static void main(String args[]){
System.out.println("All car prices:");
for (Car c : Car.values())
System.out.println(c + " costs "
+ c.getPrice() + " thousand dollars.");
}
}
Also see more demos

Getting String value from enum in Java

I have a enum defined like this and I would like to be able to obtain the strings for the individual statuses. How should I write such a method?
I can get the int values of the statuses but would like the option of getting the string values from the ints as well.
public enum Status {
PAUSE(0),
START(1),
STOP(2);
private final int value;
private Status(int value) {
this.value = value
}
public int getValue() {
return value;
}
}
if status is of type Status enum, status.name() will give you its defined name.
You can use values() method:
For instance Status.values()[0] will return PAUSE in your case, if you print it, toString() will be called and "PAUSE" will be printed.
Use default method name() as given bellows
public enum Category {
ONE("one"),
TWO ("two"),
THREE("three");
private final String name;
Category(String s) {
name = s;
}
}
public class Main {
public static void main(String[] args) throws Exception {
System.out.println(Category.ONE.name());
}
}
You can add this method to your Status enum:
public static String getStringValueFromInt(int i) {
for (Status status : Status.values()) {
if (status.getValue() == i) {
return status.toString();
}
}
// throw an IllegalArgumentException or return null
throw new IllegalArgumentException("the given number doesn't match any Status.");
}
public static void main(String[] args) {
System.out.println(Status.getStringValueFromInt(1)); // OUTPUT: START
}
I believe enum have a .name() in its API, pretty simple to use like this example:
private int security;
public String security(){ return Security.values()[security].name(); }
public void setSecurity(int security){ this.security = security; }
private enum Security {
low,
high
}
With this you can simply call
yourObject.security()
and it returns high/low as String, in this example
You can use custom values() method:
public enum SortType
{
Scored, Lasted;
public int value(){
return this == Lasted ? 1:0;
}
}

Categories

Resources