InstantiationUtil { public static <T extends IOReadableWritable> T createCopyWritable(T original) throws IOException { if (original == null) { return null; } final ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (DataOutputViewStreamWrapper out = new DataOutputViewStreamWrapper(baos)) { original.write(out); } final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); try (DataInputViewStreamWrapper in = new DataInputViewStreamWrapper(bais)) { @SuppressWarnings("unchecked") T copy = (T) instantiate(original.getClass()); copy.read(in); return copy; } } private  InstantiationUtil(); static T instantiate(Class<T> clazz, Class<? super T> castTo); static T instantiate(Class<T> clazz); static boolean hasPublicNullaryConstructor(Class<?> clazz); static boolean isPublic(Class<?> clazz); static boolean isProperClass(Class<?> clazz); static boolean isNonStaticInnerClass(Class<?> clazz); static void checkForInstantiation(Class<?> clazz); static String checkForInstantiationError(Class<?> clazz); static T readObjectFromConfig(Configuration config, String key, ClassLoader cl); static void writeObjectToConfig(Object o, Configuration config, String key); static byte[] serializeToByteArray(TypeSerializer<T> serializer, T record); static T deserializeFromByteArray(TypeSerializer<T> serializer, byte[] buf); static T deserializeFromByteArray(TypeSerializer<T> serializer, T reuse, byte[] buf); @SuppressWarnings("unchecked") static T deserializeObject(byte[] bytes, ClassLoader cl); @SuppressWarnings("unchecked") static T deserializeObject(InputStream in, ClassLoader cl); @SuppressWarnings("unchecked") static T deserializeObject(byte[] bytes, ClassLoader cl, boolean isFailureTolerant); @SuppressWarnings("unchecked") static T deserializeObject(InputStream in, ClassLoader cl, boolean isFailureTolerant); static byte[] serializeObject(Object o); static void serializeObject(OutputStream out, Object o); static boolean isSerializable(Object o); static T clone(T obj); static T clone(T obj, ClassLoader classLoader); static T createCopyWritable(T original);  }
@Test public void testCopyWritable() throws Exception { WritableType original = new WritableType(); WritableType copy = InstantiationUtil.createCopyWritable(original); assertTrue(original != copy); assertTrue(original.equals(copy)); }