1

I have 2 packages , A and B which contain the same list of classes. I am not able to use dozer or any mapping tool directly because the Enum values are uppercase in one package and camelcase in another package. I want to write a generic method which takes in the enum from package A and convert it into enum in package B using Reflection. Below is the specific code that I had written -

return a.CardType.valueOf(((b.CardType)source).getValue().toUpperCase());

I want to write generic code to convert assuming I have source class ( enum type) as object , source class name and destination class name

1
  • Sorry , I want to write generic code to convert assuming I have source class ( enum type) as object , source class name and destination class name Commented Jan 14, 2016 at 15:31

1 Answer 1

2

is that what you want

public class Mango {
    static enum Upper {A,B,C}
    static enum Lower {a,b,c}


    static <SRC extends Enum<SRC>,DST extends Enum<DST>> DST convert(SRC a, Class<DST> classDst ){
        return  Enum.valueOf(   classDst,a.name().toUpperCase());
    }

    public static void main(String[] args) {
        System.out.print(convert(Lower.a,Upper.class));
    }

}

EDIT:

So you want convert lowercase/uppercase enum to camelCase? Just modify convert function to :

static <SRC extends Enum<SRC>,DST extends Enum<DST>> DST convert(SRC a, Class<DST> classDst ){
        for (DST dst : EnumSet.allOf(classDst)){
            if (dst.name().equalsIgnoreCase(a.name())){
                return dst;
            }
        }
        throw new IllegalArgumentException("Value not found");
    }
Sign up to request clarification or add additional context in comments.

6 Comments

If the target is not just exactly the source in uppercase you also have the classDst.getEnumConstants() available for scanning.
@OldCurmudgeon or you could use EnumSet.allOf(classDst) to verify, but if they are not same you might not get away with generic converter anyway
Thank you very much. Sorry there is one challenge which I didn't notice when I posted. Enums in package A are defined in camel case.
@PunterVicky wait, are you converting from camel case to upper/lower case, or form upper/lower case? if you convert from camelCase to uppercase then first solution will works. second solution works in both directions
I'm converting from camel case to uppercase and in the reverse direction as well. Both enum classes are in different packages.
|

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.