开发者

How do I "valueOf" an enum given a class name?

开发者 https://www.devze.com 2023-01-02 15:21 出处:网络
Lets say I have a simple Enum called Animal defined as: public enum Animal { CAT, DOG } and I have a method like:

Lets say I have a simple Enum called Animal defined as:

public enum Animal {
    CAT, DOG
}

and I have a method like:

private static Object valueOf(String value, Class<?> classType) {
    if (classType == String.class) {
        return value;
    }

    if (classType == Integer.class) {
        return Integer.parseInt(value);
    }

    if (classType == Long.class) {
        return Long.parseLong(value);
    }

    if (classType == Boolean.class) {
        return Boolean.parseBoolean(value);
  开发者_如何学JAVA  }

    // Enum resolution here

}

What can I put inside this method to return an instance of my enum where the value is of the classType?

I have looked at trying:

    if (classType == Enum.class) {
        return Enum.valueOf((Class<Enum>)classType, value);
    }

But that doesn't work.


Your classType isn't Enum, it's Animal. So,

if (classType.isEnum()) {
    return Enum.valueOf(classType, value);
}

should work. Additionally, you ought to use equals() rather than == for comparing the class instances (although == will work in practice, if there's just one classloader around).

0

精彩评论

暂无评论...
验证码 换一张
取 消