0

I know my use case seem silly but this is the easiest way to explain what i need so here it goes

lets say i want to write the following silly generic methods :

void toString(Object o);

Object fromString(String enumObject,Class<Enum> classOfTheObject);

given :

public enum PositionType 
{
    B,
    F,
    L,
    R
}

and :

PositionType ptype = PositionType.B;

how do i go on and implement those methods so that :

fromString(toString(ptype),PositionType.class).equals(PositionType.B);

would return true?

i tried looking at the java reflections tutorial, but still i didnt find how to solve it there...

please notice that the implementation must not rely on the specific enum type, it could be any enum type, but for what i need, we can limit ourselves to only enum objects.

1 Answer 1

1

You can achieve this with many solutions, here is one of them (I wrote the strict minimum):

String toString(Object o) {
   return ((Enum) o).name();
}

<T extends Enum<T>> Object fromString(Class<T> enumType, String o) {
   return Enum.valueOf(enumType, o);
}
Sign up to request clarification or add additional context in comments.

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.