/** returns a map of all fields which are annotated 'SetFromFlag' with their current values; * useful if you want to clone settings from one object */ public static Map<String,Object> getFieldsWithValues(Object o) { try { Map<String, Object> result = Maps.newLinkedHashMap(); for (Map.Entry<Field, SetFromFlag> entry : getAnnotatedFields(o.getClass()).entrySet()) { Field f = entry.getKey(); SetFromFlag cf = entry.getValue(); String flagName = elvis(cf.value(), f.getName()); if (groovyTruth(flagName)) { if (!f.isAccessible()) f.setAccessible(true); result.put(flagName, f.get(o)); } } return result; } catch (IllegalAccessException e) { throw Throwables.propagate(e); } }
/** * @throws an IllegalStateException if there are fields required (nullable=false) which are unset * @throws wrapped IllegalAccessException */ public static void checkRequiredFields(Object o) { try { Set<String> unsetFields = Sets.newLinkedHashSet(); for (Map.Entry<Field, SetFromFlag> entry : getAnnotatedFields(o.getClass()).entrySet()) { Field f = entry.getKey(); SetFromFlag cf = entry.getValue(); if (!cf.nullable()) { String flagName = elvis(cf.value(), f.getName()); if (!f.isAccessible()) f.setAccessible(true); Object v = f.get(o); if (v==null) unsetFields.add(flagName); } } if (groovyTruth(unsetFields)) { throw new IllegalStateException("Missing required "+(unsetFields.size()>1 ? "fields" : "field")+": "+unsetFields); } } catch (IllegalAccessException e) { throw Throwables.propagate(e); } }
@Test public void testGetAnnotatedFields() throws Exception { Map<Field, SetFromFlag> fm = FlagUtils.getAnnotatedFields(WithImmutableNonNullableObject.class); assertEquals(fm.keySet().size(), 2); assertTrue(fm.get(WithImmutableNonNullableObject.class.getDeclaredField("b")).immutable()); }