So I was able to create this with the link @Aditya mentioned and improvising based on my use case:
//Here key = "com.order.getItems().get(0).getId().getItemId()"
//instance = createOrder(); // instance with some values populated
public String getValue(String key, Object instance) {
String[] valuePath = key.split("\\.");
int serviceTypeIndex = 0;
if (valuePath[serviceTypeIndex].equalsIgnoreCase("com")) {
try {
Class clz = Class.forName(dataConfig.getOrder()); // FQ class name passed as string so "com.example.abc.Order" in my case
Object obj = getValueHelper(clz, instance, valuePath);
if (obj != null) {
return obj.toString();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return null;
}
private Object getValueHelper(Class<?> clazz, Object instance, String[] valuePath) {
int valuePathCounter = 2;
while (valuePathCounter < valuePath.length) {
try {
if (!methodExists(clazz, valuePath[valuePathCounter])) {
return null;
}
Method m = clazz.getMethod(valuePath[valuePathCounter]);
if (m.invoke(instance) == null) {
return null;
}
instance = m.invoke(instance);
clazz = instance.getClass();
valuePathCounter++;
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
return null;
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
return instance;
}
private boolean methodExists(Class<?> clazz, String method) {
try {
clazz.getMethod(method);
} catch (NoSuchMethodException e) {
return false;
}
return true;
}