Ok, I got downvotedJust for completeness, so I looked at the question more closelyfollowing is a Java solution. This person wants to I am certain the same could be able to accept a Stringdone in C# as a parameter and magically hookwell. It avoids having to specify the type anywhere in code - instead, you specify it upin the strings you are trying to a given enumerated valueparse.
The problem is that there isn't any way to know which enumeration the String might match - so the answer is to solve that problem.
Instead of accepting just the string value, accept a String that has both the enumeration and the value in the form "enumeration.value". Working code is below - requires Java 1.8 or later. This would also make the XML more precise as in you would see something like color="Color.red" instead of just color="red".
You would call the acceptEnumeratedValue() method with a string containing the enum name dot value name. The
The method returns the formal enumerated value.
import java.util.HashMap; import java.util.Map; import java.util.function.Function; public class EnumFromString { enum NumberEnum {One, Two, Three}; enum LetterEnum {A, B, C}; Map<String, Function<String, ? extends Enum>> enumsByName = new HashMap<>(); public static void main(String[] args) { EnumFromString efs = new EnumFromString(); System.out.print("\nFirst string is NumberEnum.Two - enum is " + efs.acceptEnumeratedValue("NumberEnum.Two").name()); System.out.print("\nSecond string is LetterEnum.B - enum is " + efs.acceptEnumeratedValue("LetterEnum.B").name()); } public EnumFromString() { enumsByName.put("NumberEnum", s -> {return NumberEnum.valueOf(s);}); enumsByName.put("LetterEnum", s -> {return LetterEnum.valueOf(s);}); } public Enum acceptEnumeratedValue(String enumDotValue) { int pos = enumDotValue.indexOf("."); String enumName = enumDotValue.substring(0, pos); String value = enumDotValue.substring(pos + 1); Enum enumeratedValue = enumsByName.get(enumName).apply(value); return enumeratedValue; } }