简体   繁体   中英

Create Java enum by type and value as strings

I have defined in an XML something like :

<Property>
   <value>APPLE</value>
   <enum>com.mycompany.MyEnum</enum>
</Property>

I try to instantiate that enum in code. here is what I have so far

Class<?> clazz = Class.forName(pProperty.getEnum());
if (!clazz.isEnum())
   throw new IllegalArgumentException(MessageFormat.format("Class %s is not an enumeration.", pProperty.getEnum()));

After that, I try to call valueOf(java.lang.String), but I got a NoSuchMethodException

MyEnum is defined like this :

package com.mycompany;
public enum MyEnum
{
   APPLE, PEER, LEMON
}

Is it possible to do that ?

Thanks

Not sure if that is what you mean but if you want to get enum constant like APPLE from enum described in <enum>com.mycompany.MyEnum</enum> you can try something like this

@SuppressWarnings("rawtypes")
Class clazz = Class.forName("com.mycompany.MyEnum");
if (clazz.isEnum()) {
    @SuppressWarnings("unchecked")
    Enum<?> o = Enum.valueOf(clazz, "PEER");
    System.out.println(o.name());
    System.out.println(o.ordinal());
}

这为我工作:

clazz.getMethod("valueOf", String.class).invoke(null, "APPLE")

The following methods read from an array of properties files to get an enum's value. You should be able to adapt them to read from an XML file:

    public static <T extends Enum<?>> T getEnumProperty(String key, Class<T> type, T defVal, Properties... properties)
    {
        String val = getProperty(key, properties);
        if(val == null)
        {
            System.out.println("Using default value for: " + key);
            return defVal;
        }

        T[] enums = type.getEnumConstants();
        for(T e : enums)
        {
            if(e.name().equals(val))
            return e;
        }

        System.out.println("Illegal enum value '" + val + "' for " + key);
        return defVal;
    }

    private static String getProperty(String key, Properties... properties)
    {
        for(Properties p : properties)
        {
            String val = p.getProperty(key);
            if(val != null)
            {
                val = val.trim();
            }
            return val;
        }

        return null;
    }

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