SQLElement: better error handling of the get method + A nullable field that is not set will return null instead of throwing an exception.

This commit is contained in:
Marc Baloup 2023-08-24 12:40:38 +02:00
parent f16389d33d
commit 9ac7a98257

View File

@ -241,17 +241,24 @@ public abstract class SQLElement<E extends SQLElement<E>> {
* Gets the value of the provided field in this entry. * Gets the value of the provided field in this entry.
* @param field the field to get the value from. * @param field the field to get the value from.
* @return the value of the provided field in this entry. * @return the value of the provided field in this entry.
* @throws IllegalArgumentException if the provided field is null or not from the table represented by this class.
* @throws IllegalStateException if the field is not nullable and there is no value set
* @param <T> the Java type of the field. * @param <T> the Java type of the field.
*/ */
public <T> T get(SQLField<E, T> field) { public <T> T get(SQLField<E, T> field) {
if (field == null) throw new IllegalArgumentException("field can't be null"); if (field == null)
throw new IllegalArgumentException("field can't be null");
if (!fields.containsKey(field.getName()) || !fields.get(field.getName()).equals(field))
throw new IllegalArgumentException("The provided field " + field + " is not from this table " + getClass().getName());
if (values.containsKey(field)) { if (values.containsKey(field)) {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
T val = (T) values.get(field); T val = (T) values.get(field);
return val; return val;
} }
throw new IllegalArgumentException("The field '" + field.getName() + "' in this instance of " + getClass().getName() if (field.nullable)
+ " does not exist or is not set"); return null;
throw new IllegalStateException("The non-nullable field '" + field.getName() + "' in this instance of " + getClass().getName()
+ " is not set");
} }
/** /**