枚举具有用于获取枚举常量的valueOf(string)方法,以及名称为java.lang.EnumvalueOf(enumClassName, string)类中存在的相同类型的方法
我发现两者都给出了相同的输出。那还有什么其他区别。如果没有区别,那么为什么JSL添加Enum.valueOf()

enum Season {
    WINTER,SUMMER
}

class Test {
    public static void main(String[] args) {
        String season = "WINTER";

        //switch (Season.valueOf(colObject))  // following line achieves same thing
        switch (Enum.valueOf(Season.class, season)) // any other difference between both approach
        {
            case WINTER: {
                System.out.println("Got it in switch case= VENDOR");
                break;
            }
            default:
                System.out.println("Fell thru.");
                break;
            }
    }
}

最佳答案

之所以包含Enum.valueof()方法,是因为它可以与任何enum一起使用。相比之下,特定方法的enum valueof方法仅适用于该特定enum ...,因为enum类不能被多态使用。

显然,只有在实现需要针对多种Enum.valueOf(...)类型工作的代码时,enum方法才真正有用……而泛型却不会削减它。

09-30 15:37
查看更多