All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.infinispan.commons.util.ObjectDuplicator Maven / Gradle / Ivy

There is a newer version: 15.1.0.Dev04
Show newest version
package org.infinispan.commons.util;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;


/**
 * A helper that efficiently duplicates known object types.
 *
 * @author (various)
 * @deprecated Since 12, will be removed in version 15.0
 */
@Deprecated(forRemoval = true)
public class ObjectDuplicator {
   @SuppressWarnings("unchecked")
   public static  Map duplicateMap(Map original) {
      if (original instanceof FastCopyHashMap)
         return ((FastCopyHashMap) original).clone();
      if (original instanceof HashMap)
         return (Map) ((HashMap) original).clone();
      if (original instanceof TreeMap)
         return (Map) ((TreeMap) original).clone();
      if (original.getClass().equals(Collections.emptyMap().getClass()))
         return Collections.emptyMap();
      if (original.getClass().equals(Collections.singletonMap("", "").getClass())) {
         Map.Entry e = original.entrySet().iterator().next();
         return Collections.singletonMap(e.getKey(), e.getValue());
      }
      return attemptClone(original);
   }

   @SuppressWarnings("unchecked")
   public static  Set duplicateSet(Set original) {
      if (original instanceof HashSet)
         return (Set) ((HashSet) original).clone();
      if (original instanceof TreeSet)
         return (Set) ((TreeSet) original).clone();
      if (original instanceof FastCopyHashMap.EntrySet || original instanceof FastCopyHashMap.KeySet)
         return new HashSet<>(original);
      if (original.getClass().equals(Collections.emptySet().getClass()))
         return Collections.emptySet();
      if (original.getClass().equals(Collections.singleton("").getClass()))
         return Collections.singleton(original.iterator().next());
      if (original.getClass().getSimpleName().contains("$"))
         return new HashSet<>(original);

      return attemptClone(original);
   }

   @SuppressWarnings("unchecked")
   public static  Collection duplicateCollection(Collection original) {
      if (original instanceof HashSet)
         return (Set) ((HashSet) original).clone();
      if (original instanceof TreeSet)
         return (Set) ((TreeSet) original).clone();

      return attemptClone(original);
   }

   @SuppressWarnings("unchecked")
   private static  T attemptClone(T source) {
      if (source instanceof Cloneable) {
         try {
            return (T) source.getClass().getMethod("clone").invoke(source);
         }
         catch (Exception e) {
            // Will return null
         }
      }

      return null;
   }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy