Returning a string literal from an Enum - java

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

Related

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.

Can I reference a class by String name?

I have a list of utilities that derive from:
abstract public class BaseUtil implements Callable{
public String name;
public StreamWrapper data;
public void setData(StreamWrapper stream){ this.data = stream; }
private static Class me = BaseUtil.class;
private static Method[] availableUtilities = me.getDeclaredMethods();
public static Method[] getUtilities(){ return availableUtilities; }
}
I want to, at each node, be able to assign a utility to it, something like:
Initialize(String utilName){
activeUtility = utilName;
gk = new GateKeeper(BaseUtil.getUtilities() <something>);
}
public class GateKeeper {
GateKeeper(BaseUtil util) {
this.util = util;
}
private BaseUtil util;
But I'm unsure on how to get the specific utility class from just the String passed in. An example utility is:
public class WordLengthUtil extends BaseUtil {
private String name = "WordLength";
public Integer call() {
System.out.println(this.data);
return Integer.valueOf(this.data.length());
}
}
You can use reflection:
String name = "WordLength";
String className = hashMap.get(name);
Callable plugin = (Callable) Class.forName(className).newInstance();
use HashMap to store binding between className and string identifier

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;
}
}

Using enums in 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;
}

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