public static Pair<Class<?>, Field> getAnyField(Class<?> clazz, String fieldName) { try { return new Pair<Class<?>, Field>(clazz, clazz.getDeclaredField(fieldName)); } catch (SecurityException e) { throw new CloudRuntimeException("How the heck?", e); } catch (NoSuchFieldException e) { // Do I really want this? No I don't but what can I do? It only throws the NoSuchFieldException. Class<?> parent = clazz.getSuperclass(); if (parent != null) { return getAnyField(parent, fieldName); } return null; } }
public void addOrderBy(Class<?> clazz, String field, boolean ascending) { if (field == null) { return; } Field f; Pair<Class<?>, Field> pair = ReflectUtil.getAnyField(clazz, field); assert (pair != null) : "Can't find field " + field + " in " + clazz.getName(); clazz = pair.first(); f = pair.second(); Column column = f.getAnnotation(Column.class); String name = column != null ? column.name() : field; StringBuilder order = new StringBuilder(); if (column == null || column.table() == null || column.table().length() == 0) { order.append(DbUtil.getTableName(clazz)); } else { order.append(column.table()); } order.append(".").append(name).append(ascending ? " ASC " : " DESC "); if (_orderBy == null) { _orderBy = order.insert(0, " ORDER BY ").toString(); } else { _orderBy = order.insert(0, _orderBy + ", ").toString(); } }
public static Pair<Class<?>, Field> getAnyField(final Class<?> clazz, final String fieldName) { try { return new Pair<>(clazz, clazz.getDeclaredField(fieldName)); } catch (final SecurityException e) { throw new CloudRuntimeException("How the heck?", e); } catch (final NoSuchFieldException e) { // Do I really want this? No I don't but what can I do? It only throws the NoSuchFieldException. final Class<?> parent = clazz.getSuperclass(); if (parent != null) { return getAnyField(parent, fieldName); } return null; } }
public void addOrderBy(Class<?> clazz, final String field, final boolean ascending) { if (field == null) { return; } final Field f; final Pair<Class<?>, Field> pair = ReflectUtil.getAnyField(clazz, field); assert (pair != null) : "Can't find field " + field + " in " + clazz.getName(); clazz = pair.first(); f = pair.second(); final Column column = f.getAnnotation(Column.class); final String name = column != null ? column.name() : field; final StringBuilder order = new StringBuilder(); if (column == null || column.table() == null || column.table().length() == 0) { order.append(DbUtil.getTableName(clazz)); } else { order.append(column.table()); } order.append(".").append(name).append(ascending ? " ASC " : " DESC "); if (_orderBy == null) { _orderBy = order.insert(0, " ORDER BY ").toString(); } else { _orderBy = order.insert(0, _orderBy + ", ").toString(); } }