Tuesday, April 14, 2009

Java Bean validation using reflection


public static boolean validateBeanFields(Object obj) {

if (obj == null)
return false;

Class objClass = obj.getClass();
Method[] methods = objClass.getMethods();
for (Method aMethod : methods) {
String methodName = aMethod.getName();
if (methodName.startsWith("get")) {
try {
Object retObj = aMethod.invoke(obj, null);

if (retObj == null)
return false;
else if (retObj instanceof Enum) // skip enum values
continue;
else if (retObj instanceof String) {
if (((String)retObj).length() == 0)
return false;
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
return true;
}

No comments:

Post a Comment