@SuppressWarnings("unchecked") public static <T> T singleton(Class<T> clazz) { Object instance = SINGLETONS.get(clazz); if (instance == null) { instance = instantiate(clazz); SINGLETONS.put(clazz, instance); } return (T) instance; }
public static Object getPropValue(Object instance, String propertyName) { String propertyNameCap = U.capitalize(propertyName); try { for (Class<?> c = instance.getClass(); c != Object.class; c = c.getSuperclass()) { try { return invoke(c.getDeclaredMethod(propertyName), instance); } catch (NoSuchMethodException e) { try { return invoke(c.getDeclaredMethod("get" + propertyNameCap), instance); } catch (NoSuchMethodException e2) { try { return invoke(c.getDeclaredMethod("is" + propertyNameCap), instance); } catch (NoSuchMethodException e3) { try { return getFieldValue(c.getDeclaredField(propertyName), instance); } catch (NoSuchFieldException e4) { // keep searching in the super-class... } } } } } } catch (Exception e) { throw Errors.rte("Cannot get property value!", e); } throw Errors.rte("Cannot find the property '%s' in the class '%s'", propertyName, instance.getClass()); }
public static Object getFieldValue(Object instance, String fieldName) { try { for (Class<?> c = instance.getClass(); c != Object.class; c = c.getSuperclass()) { try { Field field = c.getDeclaredField(fieldName); return getFieldValue(field, instance); } catch (NoSuchFieldException e) { // keep searching the filed in the super-class... } } } catch (Exception e) { throw Errors.rte("Cannot get field value!", e); } throw Errors.rte("Cannot find the field '%s' in the class '%s'", fieldName, instance.getClass()); }
public static long getId(Object obj) { Object id = ClassUtils.getPropValue(obj, "id"); if (id == null) { throw Errors.rte("The field 'id' cannot be null!"); } if (id instanceof Long) { Long num = (Long) id; return num; } else { throw Errors.rte("The field 'id' must have type 'long', but it has: " + id.getClass()); } }