简体   繁体   中英

(Error: valueOf(Class<T>, String) of type Enum<E> but does not hide it) Upgrade version from jdk1.6 to jdk1.7

When I have upgrade java version from jdk1.6 to jdk1.7 in eclipse, The below error has started to throw in compile mode only.

The error is:

Name clash: The method valueOf(Class, String) of type TestEnum has the same erasure as valueOf(Class, String) of type Enum but does not hide it

public enum TestEnum {
    ABC;
    public static TestEnum valueOf(Class<TestEnum> enumType, String value){//This error throw at this line.
        return null;

    };

}

When I have changed compile level from 1.7 to 1.6, error has gone. I do't understand why is this not working with compile level 1.7? is there any other changes need to compile level 1.7?

Edit:

It returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type. but I have not such case, the name is different.There are above 100 enum classes which has same implementation. it is not easy for me to change such product wide change.

public enum TestEnum {
    ABC;
    public String toString() {
        switch (this) {
        case ABC:
            return "Abc";
        }
        return "";
    }
/*  public static TestEnum valueOf(Class<TestEnum> enumType, String value){
        if(value.equalsIgnoreCase("XYZ")){
            return ABC;
        }
        return null;

    };*/

    public static void main(String[] args) {
        TestEnum t=TestEnum.valueOf(TestEnum.class,"Abc");
        System.out.println(t);

    }

}

> Exception in thread "main" java.lang.IllegalArgumentException: No enum constant com.test.example.TestEnum.Abc at java.lang.Enum.valueOf(Enum.java:236) at com.test.example.TestEnum.main(TestEnum.java:22)

The problem is that static <T extends Enum<T>> T Enum.valueOf(Class<T> enumType, String name) is not the same as your public static TestEnum valueOf(Class<TestEnum> enumType, String value) , but look the same after type erasure (both essentially become static Object valueOf(Class enumType, String value).

Since this can lead to unintuitive behavior, the Java creators decided that this should be an error; the corresponding check was implemented in Java 1.7. If your valueOf method behaves (or should behave) like Enum.valueOf , you can simply remove it. Otherwise, renaming it could solve the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM