You can use reflection. Here is an example:
public String matchMethod(MyEnum myenum, Map<MyEnum, String> enumToFieldMap) throws NoSuchFieldException, IllegalAccessException {
String customFieldName = enumToFieldMap.get(myenum);
if (customFieldName == null) { // custom field name not found, use default mapping
return (String) this.getClass().getDeclaredField(myenum.name().toLowerCase()).get(this);
} // custom field name found in config
return (String) this.getClass().getDeclaredField(customFieldName).get(this);
}
public String matchMethod(MyEnum myEnum) throws NoSuchFieldException, IllegalAccessException {
return matchMethod(myEnum, Collections.EMPTY_MAP);
}
There are some drawbacks of using reflection like type safety or traceability, however in this case I think I would choose this option.
Another, much more flexible option is to use reflection combined with custom annotation:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyEnumRef {
MyEnum value();
}
And common interface:
public interface Pojo {
}
Declaring new Pojo
(s) becomes much simpler and cleaner now, and more readable too (at least for some people). It is also very obvious where the actual mapping (configuration) is done.
public class MyPojo implements Pojo {
@MyEnumRef(MyEnum.FIELD1)
private String field1;
@MyEnumRef(MyEnum.FIELD2)
private String field2;
@MyEnumRef(MyEnum.FIELD3)
private String field3;
}
public class MyOtherPojo implements Pojo {
@MyEnumRef(MyEnum.FIELD1)
private String field1;
@MyEnumRef(MyEnum.FIELD2)
private String field2;
}
One simple method to rule them all:
public String matchMethod(MyEnum myEnum, Pojo myPojo) throws IllegalAccessException {
for (Field field : myPojo.getClass().getDeclaredFields()) {
if (field.isAnnotationPresent(MyEnumRef.class) && field.getAnnotation(MyEnumRef.class).value() == myEnum) {
field.setAccessible(true);
return (String) field.get(myPojo);
}
}
return "";
}
It doesn't matter which implementation of Pojo
you use. There is no overhead when adding new Pojos. Example:
private void run() throws IllegalAccessException {
System.out.println(">>" + matchMethod(MyEnum.FIELD2, new MyPojo("f1", "f2", "f3")));
System.out.println(">>" + matchMethod(MyEnum.FIELD1, new MyOtherPojo("o1", "o2")));
}