Skip to content

Instantly share code, notes, and snippets.

@matschaffer
Created August 25, 2009 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matschaffer/174714 to your computer and use it in GitHub Desktop.
Save matschaffer/174714 to your computer and use it in GitHub Desktop.
/**
* Helper to return the fallback as a string if the provided attribute is null or empty.
* @param attribute The desired attribute
* @param fallback The value to use if the attribute is null or an empty string.
* @return String representation of either attribute or the default
*/
protected String attributeWithFallback(Object attribute, Object fallback) {
Object selected;
if (attribute == null || StringUtils.isEmpty(attribute.toString())) {
selected = fallback;
} else {
selected = attribute;
}
List<Method> methods = Arrays.asList(selected.getClass().getMethods());
String desiredMethod = "value";
try {
for (Method method : methods) {
if (method.getName().equals(desiredMethod) && method.getReturnType() == String.class) {
return (String)method.invoke(selected);
}
}
} catch (IllegalAccessException e) {} catch (InvocationTargetException e) {}
return selected.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment