2

我的 Android 应用程序使用枚举类型来定义某些 API 端点。

public static enum API_ENDPOINT{
        MISSION, FEATURED_MEDIA
}

对于依赖于 API 调用类型的方法,枚举类型似乎是一个合适的参数,但我无法跨使用不同语言配置的设备将枚举转换为一致的字符串(即映射到 API 端点 url)。

在土耳其API_ENDPOINT.values()退货中:mıssıon, featured_medıa

用英语API_ENDPOINT.values()返回:mission, featured_media

一个明显的解决方案是映射API_ENDPOINT到硬编码字符串端点的附加数据结构,但我很好奇这种行为是否enum.values()是有意的和/或可避免的。

已解决:感谢大家的洞察力。事实证明,在没有指定语言环境的情况下转换API_ENDPOINT为我使用的 URL 字符串的逻辑更深String.toLowerCase(),这导致了不良行为。这已被替换为String.toLowerCase(Locale.US)

4

2 回答 2

2

You can hard-code the strings as part of the enum, without any additional data structure:

public static enum API_ENDPOINT{
    MISSION("mission"), FEATURED_MEDIA("featured_media");
    private final String value;
    API_ENDPOINT(String value) { this.value = value; }
    public String value() { return value; }
}

but it would be nice if there were just a way to control the representation that's automatically generated.

The JLS enum section doesn't speak directly to language differences like this, but strongly suggests that the output would exactly match the enum identifiers; I'm surprised that you'd even get lower-case strings with upper-case identifiers.


After further testing, this isn't reproducible, something else must be going on in your code.

This minimal program displays the enum identifiers exactly as typed regardless of locale:

public class MainActivity extends Activity {
    public enum ENUM {
        MISSION, FEATURED_MEDIA
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView textView = (TextView) findViewById(R.id.text);
        String enums = "";
        for (ENUM e : ENUM.values()) {
            enums += e + " ";
        }
        textView.setText(enums);
    }
}
于 2013-10-30T18:32:26.583 回答
2

您可以定义两个属性文件。一种用于英语,一种用于土耳其语。
枚举可能看起来像这样:

public static enum API_ENDPOINT{
    MISSION("path.to.property.mission"), FEATURED_MEDIA("path.to.property.featured_media");

    private String propertyName;
    API_ENDPOINT(String propertyName){
        this.propertyName = propertyName;
    }

    // language could also be an enum which defines the language to be taken
    // and should contain the path to the file.
    public String getTranslatedText(Language language){
        Properties prop = new Properties();

        try {
            //load a properties file from class path
            prop.load(API_ENDPOINT.class.getClassLoader().getResourceAsStream(language.getPropertyFileName()));

            //get the translated value and raturn it.
            return prop.getProperty(propertyName);

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

属性文件将如下所示(英文):

path.to.property.mission=Mission
path.to.property.featured_media=Featured Media

土耳其语也是如此。希望有帮助。

编辑:由于您使用的是 Android,这可能是您的问题的解决方案:

于 2013-10-30T18:28:42.140 回答