How to get value from a Java enum - java

I have a enum which looks like:
public enum Constants{
YES("y"), NO("N")
private String value;
Constants(String value){
this.value = value;
}
}
I have a test class which looks like
public class TestConstants{
public static void main(String[] args){
System.out.println(Constants.YES.toString())
System.out.println(Constants.NO.toString())
}
}
The output is:
YES
NO
instead of
Y
N
I am not sure what is wrong here ??

You need to override the toString method of your enum:
public enum Constants{
YES("y"), NO("N")
// No changes
#Override
public String toString() {
return value;
}
}

You can also add a getter to the enumeration and simply call on it to access the instance variable:
public enum Constants{
YES("Y"), NO("N");
private String value;
public String getResponse() {
return value;
}
Constants(String value){
this.value = value;
}
}
public class TestConstants{
public static void main(String[] args){
System.out.println(Constants.YES.getResponse());
System.out.println(Constants.NO.getResponse());
}
}

Create a getValue() method in your enum, and use this instead of toString().
public enum Constants{
YES("y"), NO("N")
private String value;
Constants(String value){
this.value = value;
}
}
public String getValue(){
return value;
}
And instead of:
System.out.println(Constants.YES.toString())
System.out.println(Constants.NO.toString())
(Which are also missing a semi-colon), use
System.out.println(Constants.YES.getValue());
System.out.println(Constants.NO.getValue());
Hope this solved your problem. If you do not want to create a method in your enum, you can make your value field public, but this would break encapsulation.

Write Getter and Setter for value and use:
System.out.println(Constants.YES.getValue());
System.out.println(Constants.NO.getValue());

String enumValue = Constants.valueOf("YES")
Java doc ref: https://docs.oracle.com/javase/7/docs/api/java/lang/Enum.html#valueOf(java.lang.Class,%20java.lang.String)

Related

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() {}
}

enum does not provide expected result

I have defined an enum in a class A
public class A{
public static final String CANDY = "yelow candy";
public static final String CAKE = "cookie";
public enum Yummy{
CANDY, CAKE;
}
}
In another package,
public class C {
Yummy[] yummies = A.Yummy.values();
for (Yummy yum : yummies){
String yumString = yum.toString();
System.out.println("yum =" + yumString);
}
}
I get CANDY and CAKE as a result, not "yelow candy" and "cookie".
What does I need to change to get the "yelow candy" and "cookie ?
You've defined an enum "A.Yummy" and also two strings, "A.Candy" and "A.CAKE".
They aren't linked at all.
You will want to delete the strings and add something like https://stackoverflow.com/a/13291109/1041364
public enum Yummy {
CANDY("yelow candy"),
CAKE("cookie");
private String description;
private Yummy(String description) {
this.description= description;
}
public String toString() {
return this.description;
}
}
Try the following:
public enum Yummy{
CANDY ("yellow candy"), CAKE ("cookie");
private String name;
private Yummy(String name) {
this.name = name;
}
public String toString() {
return this.name;
}
}
Additional values for enums should be hold in properties. You have to provide constructor to set up those properties.
public enum Yummy {
CANDY("yelow candy"), CAKE("cookie");
private String value;
private Yummy(String value) {
this.value = value;
}
};
And then in code you can use CANDY.value or override toString() method.
Try this:
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
for (Yummy yum : Yummy.values()) {
System.out.printf("%s, %s\n", yum, yum.getValue());
}
}
}
enum Yummy {
CANDY("yelow candy"),
CAKE("cookie");
private String value;
private Yummy(String value) {
this.value = value;
}
public String getValue() {
return this.value;
}
}

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

How to limit generic class parameter to certain classes

In my generic class I need to restrict type parameter to Integer OR String. Is there a way to achieve this? I cannot use T extends SomeClass to limit types, because common parent is just Object...
update
public abstract class MyClass<T>{
private T value;
public T getValue(){
return value;
}
}
I'd like the value type to be a String or an Integer and I need to use the same method to get it (not getIntValue() + getStringValue() )
This doesn't seem to help...
If I were you, I would overload two methods:
public void withInteger(Integer param) { .. }
public void withString(String param) { .. }
Note that there's no reason to use something like T extends String, because both String and Integer are final and can't be subclassed.
Just made your class ctor private and pass through a factory method to create implementation; type restriction is not bounded to MyClass but via factory.
class MyClass<T> {
private T value;
MyClass(T value) { this.value = value; }
public T getValue() { return value; }
}
class MyClassFactory {
public final static MyClass<Integer> createInteger(Integer i) {
return new MyClass<Integer>(i);
}
}

enum properties & side effects

I have a question regarding enum (it might be a simple one but ....).
This is my program:
public class Hello {
public enum MyEnum
{
ONE(1), TWO(2);
private int value;
private MyEnum(int value)
{
System.out.println("hello");
this.value = value;
}
public int getValue()
{
return value;
}
}
public static void main(String[] args)
{
MyEnum e = MyEnum.ONE;
}
}
and my question is: Why the output is
hello
hello
and not
hello
?
How the code is "going" twice to the constructor ?
When is the first time and when is the second ?
And why the enum constructor can not be public ?
Is it the reason why it print twice and not one time only ?
Enums are Singletons and they are instanciated upon loading of the class - so the two "hello"s come from instanciating MyEnum.ONE and MyEnum.TWO (just try printing value as well).
This is also the reason why the constuctor must not be public: the Enum guarantees there will ever only be one instance of each value - which it can't if someone else could fiddle with the constructor.
How the code is "going" twice to the constructor ?
Conctructor is invoked for each element of enum. Little change your example for demonstration it:
public class Hello {
public enum MyEnum {
ONE(1), TWO(2);
private int value;
private MyEnum(int value) {
this.value = value;
System.out.println("hello "+this.value);
}
public int getValue() {
return value;
}
}
public static void main(String[] args) {
MyEnum e = MyEnum.ONE;
}
}
Output:
hello 1
hello 2
Your constructor invoke twice. The moment of loading your Enum class it will invoke number of time which equals to number of enum types here.
MyEnum e = MyEnum.ONE; // singleton instance of Enum
consider following
public class Hello {
public enum MyEnum
{
ONE(1), TWO(2), THREE(3);
private int value;
private MyEnum(int value)
{
System.out.println("hello"+value);
this.value = value;
}
public int getValue()
{
return value;
}
}
public static void main(String[] args)
{
MyEnum e = MyEnum.ONE;
}
}
Out put
hello1
hello2
hello3

Categories

Resources