LoginSignup
3
3

More than 5 years have passed since last update.

大文字/小文字のString文字列からEnumの要素を取得する

Posted at

args4jというのを知って、なんでだろうと思ってたら、こんな実装をしてた。
勉強になりました。

import org.junit.Test;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

public class EnumTest {

    @Test
    public void test() throws Exception {
        String val = "local";
        Class<ENV> clazz = ENV.class;
        ENV target = null;
        for (ENV env : clazz.getEnumConstants()) {
            if(env.name().equalsIgnoreCase(val)){
                target = env;
                break;
            }
        }
        assertThat(target, is(ENV.LOCAL));
    }

    private static enum ENV {
        LOCAL,
        PRODUCTION;
    }
}
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3