/** * Make all nested objects top-level in returned collection * * @param obj a top-level object or collection of such objects * @return a set of objects * @throws Exception if a problem occurred during flattening */ public static List<Object> flatten(Object obj) throws Exception { Collection<?> c; if (obj instanceof Collection<?>) { c = (Collection<?>) obj; } else { c = Arrays.asList(new Object[] {obj}); } try { List<Object> toStore = new ArrayList<Object>(); for (Object i : c) { flatten(i, toStore); } return toStore; } catch (Exception e) { throw new Exception("Problem occurred flattening object", e); } }
/** * Make all nested objects top-level in returned collection * * @param obj a top-level object or collection of such objects * @return a set of objects * @throws Exception if a problem occurred during flattening */ public static List<Object> flatten(Object obj) throws Exception { Collection<?> c; if (obj instanceof Collection<?>) { c = (Collection<?>) obj; } else { c = Arrays.asList(new Object[] {obj}); } try { List<Object> toStore = new ArrayList<Object>(); for (Object i : c) { flatten(i, toStore); } return toStore; } catch (Exception e) { throw new Exception("Problem occurred flattening object", e); } }
private static void flatten(Object o, Collection<Object> c) throws Exception { if (o == null || c.contains(o)) { return; } c.add(o); Method[] getters = TypeUtil.getGetters(o.getClass()); for (int i = 0; i < getters.length; i++) { Method getter = getters[i]; Class<?> returnType = getter.getReturnType(); if (Collection.class.isAssignableFrom(returnType)) { for (Object obj : (Collection<?>) getter.invoke(o, new Object[] {})) { flatten(obj, c); } } else if (!returnType.isPrimitive() && !returnType.getName().startsWith("java")) { flatten(getter.invoke(o, new Object[] {}), c); } } }
private static void flatten(Object o, Collection<Object> c) throws Exception { if (o == null || c.contains(o)) { return; } c.add(o); Method[] getters = TypeUtil.getGetters(o.getClass()); for (int i = 0; i < getters.length; i++) { Method getter = getters[i]; Class<?> returnType = getter.getReturnType(); if (Collection.class.isAssignableFrom(returnType)) { for (Object obj : (Collection<?>) getter.invoke(o, new Object[] {})) { flatten(obj, c); } } else if (!returnType.isPrimitive() && !returnType.getName().startsWith("java")) { flatten(getter.invoke(o, new Object[] {}), c); } } }
private void marshalList(List list, File file) throws Exception { List flat = TypeUtil.flatten(list); System.out.println("flat = " + flat); setIds(flat); System.out.println("setIds: " + flat); binding.marshal(flat, new BufferedWriter(new FileWriter(file))); stripIds(flat); }