Java – how to give an enumeration “valueof” with a class name?
                                        
                    •
                    Java                                    
                Suppose I have a simple enum named animal, which is defined as:
public enum Animal {
    CAT,DOG
}
I have a method, such as:
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 in this method to return my enumeration instance, where value is classtype?
I've seen attempts:
if (classType == Enum.class) {
        return Enum.valueOf((Class<Enum>)classType,value);
    }
But it doesn't work
Solution
Your classtype is not enum, it is animal So,
if (classType.isEnum()) {
    return Enum.valueOf(classType,value);
}
It should work In addition, you should use equals () instead of = = to compare class instances (although = = will work in practice if there is only one class loader)
                            The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
                        
                                            
                        THE END
                    
                    
                    
                                                        二维码
                        
                        
                                                
                        