public static <D> D detach(final Object object) {
        if (object instanceof Element) {
            return (D) ReferenceFactory.detach((Element) object);
        } else if (object instanceof Property) {
            return (D) ReferenceFactory.detach((Property) object);
        } else if (object instanceof Path) {
            return (D) ReferenceFactory.detach((Path) object);
        } else if (object instanceof List) {
            final List list = new ArrayList(((List) object).size());
            for (final Object item : (List) object) {
                list.add(ReferenceFactory.detach(item));
            }
            return (D) list;
        } else if (object instanceof BulkSet) {
            final BulkSet set = new BulkSet();
            for (Map.Entry<Object, Long> entry : ((BulkSet<Object>) object).asBulk().entrySet()) {
                set.add(ReferenceFactory.detach(entry.getKey()), entry.getValue());
            }
            return (D) set;
        } else if (object instanceof Set) {
            final Set set = object instanceof LinkedHashSet ?
                    new LinkedHashSet(((Set) object).size()) :
                    new HashSet(((Set) object).size());
            for (final Object item : (Set) object) {
                set.add(ReferenceFactory.detach(item));
            }
            return (D) set;
        } else if (object instanceof Map) {
            final Map map = object instanceof Tree ? new Tree() :
                    object instanceof LinkedHashMap ?
                            new LinkedHashMap(((Map) object).size()) :
                            new HashMap(((Map) object).size());
            for (final Map.Entry<Object, Object> entry : ((Map<Object, Object>) object).entrySet()) {
                map.put(ReferenceFactory.detach(entry.getKey()), ReferenceFactory.detach(entry.getValue()));
            }
            return (D) map;
        } else {
            return (D) object;
        }
    }
@author Marko A. Rodriguez (http://markorodriguez.com)
gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/reference/ReferenceFactory.java