programing

Enum 값을 문자열 리터럴로 사용

bestcode 2022. 8. 13. 12:14
반응형

Enum 값을 문자열 리터럴로 사용

Enum에 저장된 값을 문자열 리터럴로 사용하는 가장 좋은 방법은 무엇입니까?예를 들어 다음과 같습니다.

public enum Modes {
    some-really-long-string,
    mode1,
    mode2,
    mode3
}

에 럼럼 then then then then then then then then then then then then 를 사용할 수 있습니다.Mode.mode1 mode1 전화할 Mode.mode1.toString().

그럴수는 없어요.네 가지 선택지가 있는 것 같아요.네 가지 모두 해결책을 제시하지만 접근 방식이 약간 다릅니다.

옵션 1: name() 형식이 .특별한 명명 형식이 필요하지 않다면 이 방법으로도 충분합니다.

    String name = Modes.mode1.name(); // Returns the name of this enum constant, exactly as declared in its enum declaration.

옵션 2: 추가 제어를 원할 경우 Enum에 우선 속성을 추가합니다.

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

옵션 3: enum 대신 static final을 사용합니다.

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

옵션 4: 인터페이스에는 public, static 및 final의 각 필드가 있습니다.

public interface Modes {

    String MODE_1 = "Fancy Mode 1";
    String MODE_2 = "Fancy Mode 2";
    String MODE_3 = "Fancy Mode 3";  
}

에는 둘 다 .name() a. a. a.valueOf(String)「」. 하고, 반환합니다.전자는 열거형의 문자열 이름을 반환하고 후자는 이름이 문자열인 열거형 값을 반환합니다.게게당 신신 ?? ???

String name = Modes.mode1.name();
Modes mode = Modes.valueOf(name);

valueOf(Class, String)Enum을 사용하다

Modes mode = Enum.valueOf(Modes.class, name);

하면 '무엇보다 을 할 수 있습니다.toString()메서드를 지정합니다.

예:

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

}

사용방법:

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
}

Benny Neugebauer가 언급했듯이 toString()을 덮어쓸 수 있습니다.그러나 각 열거 필드의 toString을 덮어쓰는 대신 다음과 같은 것이 더 좋습니다.

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

모든 필드를 가져오거나 모두 인쇄하는 정적 메서드를 추가할 수도 있습니다.getValue를 호출하여 각 Enum 항목에 관련된 문자열을 가져옵니다.

mode1.name() ★★★★★★★★★★★★★★★★★」String.valueOf(mode1)는 않을 그 이상 좋아지지는 않을 것이다.

public enum Modes {
  MODE1("Mode1"),
  MODE2("Mode2"),
  MODE3("Mode3");

 private String value;
 public String getValue() {
    return value;
   }
 private Modes(String value) {
  this.value = value;
 } 
}

다음과 같은 콜을 발신할 수 있습니다.이 값은 열거형에서 스트링으로 취득할 수 있습니다.

Modes.MODE1.getvalue();

그러면 "Mode1"이 문자열로 반환됩니다.

내 enum에 대해서는 각각 1 String이 할당되는 것을 별로 좋아하지 않습니다.이것이 enum에 toString() 메서드를 구현하는 방법입니다.

enum Animal
{
    DOG, CAT, BIRD;
    public String toString(){
        switch (this) {
            case DOG: return "Dog";
            case CAT: return "Cat";
            case BIRD: return "Bird";
        }
        return null;
    }
}

하시면 됩니다.Mode.mode1.name()하지만 이렇게 할 필요가 없는 경우가 많습니다.

Mode mode =
System.out.println("The mode is "+mode);

제가 알기로는 이름을 알 수 있는 유일한 방법은

Mode.mode1.name();

단, 이 방법이 정말로 필요한 경우에는 다음과 같이 할 수 있습니다.

public enum Modes {
    mode1 ("Mode1"),
    mode2 ("Mode2"),
    mode3 ("Mode3");

    private String name;       

    private Modes(String s) {
        name = s;
    }
}

다음과 같이 간단하게 할 수 있습니다.

""+ Modes.mode1

당신의 문제에 대한 나의 해결책!

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!");

    }
}

Enum은 단지 조금 특별한 클래스입니다.에넘은 추가 필드, 구현 메서드 등을 저장할 수 있습니다.예를들면

public enum Modes {
    mode1('a'),
    mode2('b'),
    mode3('c'),
    ;
    char c;

    private Modes(char c) {
        this.c = c;
    }
    public char character() {
        return c;
    }
}

이제 다음과 같이 말할 수 있습니다.

System.out.println(Modes.mode1.character())

「」를 해 주세요.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;
    }



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

다음과 같이 출력됩니다.

https://prod.domain.com:1088/

열거 문자열 상수에 대한 이 설계는 대부분의 경우에 작동합니다.

이 방법은 모든 경우에 사용할 수 있습니다.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();
    }
}

이것이 타입 오류를 방지하는 데 더 용이하다는 것을 알게 되었습니다.

public enum Modes {
    some-really-long-string,
    mode1,
    mode2,
    mode3;

    String str;

    Modes(){
        this.str = super.name();
    }

    @Override
    @NonNull
    public String toString() {
        return str;
    }

단, 이것은 log/println에서 String을 사용해야 하는 경우 또는 java가 toString() 메서드를 자동으로 컴파일할 때 이와 같은 코드라인 상에서 동작합니다.->

// sample method that require (string,value)
intent.putExtra(Modes.mode1 ,shareElement.getMode()); // java error
// first argument enum does not return value

대신 위에서 설명한 바와 같이 열거형을 확장하여 다음과 같은 경우에 사용해야 합니다.

intent.putExtra(Modes.mode1.name() ,shareElement.getMode()); 

많은 시도 끝에 나는 이 해결책을 생각해 냈다.

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

다음과 같이 시험해 보십시오.

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

}

사용하다mode1.name()또는String.valueOf(Modes.mode1)

언급URL : https://stackoverflow.com/questions/6667243/using-enum-values-as-string-literals

반응형