0

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

1
  • 2
    Please show the code which fails. Commented Oct 28, 2013 at 16:23

3 Answers 3

1

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());
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! It is working now. I dont get everything but it looks that the trick was to declare clazz as class, not as class<?> like I did.
0

This worked for me:

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.