tags:

views:

74

answers:

1

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);
    }

    // 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.

+5  A: 

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).

Joonas Pulakka
But Class doesn't override equals(), so I guess equals() won't work either if there are multiple class loaders.
waxwing
Umm, I guess you're right. Actually I don't know how multiple class loaders work together, nor if it's actually likely (or even possible) that there are multiple instances of the same class object around. Perhaps `Class#isAssignableFrom()` could be used too. That said, using `equals()` is hardly wrong.
Joonas Pulakka