CloneUtils.java revision 069490a5ca2fd1988d29daf45d892f47ad665115
1/*
2 * $HeadURL:$
3 * $Revision:$
4 * $Date:$
5 *
6 * ====================================================================
7 *
8 *  Licensed to the Apache Software Foundation (ASF) under one or more
9 *  contributor license agreements.  See the NOTICE file distributed with
10 *  this work for additional information regarding copyright ownership.
11 *  The ASF licenses this file to You under the Apache License, Version 2.0
12 *  (the "License"); you may not use this file except in compliance with
13 *  the License.  You may obtain a copy of the License at
14 *
15 *      http://www.apache.org/licenses/LICENSE-2.0
16 *
17 *  Unless required by applicable law or agreed to in writing, software
18 *  distributed under the License is distributed on an "AS IS" BASIS,
19 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 *  See the License for the specific language governing permissions and
21 *  limitations under the License.
22 * ====================================================================
23 *
24 * This software consists of voluntary contributions made by many
25 * individuals on behalf of the Apache Software Foundation.  For more
26 * information on the Apache Software Foundation, please see
27 * <http://www.apache.org/>.
28 *
29 */
30package org.apache.http.client.utils;
31
32import java.lang.reflect.InvocationTargetException;
33import java.lang.reflect.Method;
34
35/**
36 * A collection of utilities to workaround limitations of Java clone framework.
37 */
38public class CloneUtils {
39
40    public static Object clone(final Object obj) throws CloneNotSupportedException {
41        if (obj == null) {
42            return null;
43        }
44        if (obj instanceof Cloneable) {
45            Class<?> clazz = obj.getClass ();
46            Method m;
47            try {
48                m = clazz.getMethod("clone", (Class[]) null);
49            } catch (NoSuchMethodException ex) {
50                throw new NoSuchMethodError(ex.getMessage());
51            }
52            try {
53                return m.invoke(obj, (Object []) null);
54            } catch (InvocationTargetException ex) {
55                Throwable cause = ex.getCause();
56                if (cause instanceof CloneNotSupportedException) {
57                    throw ((CloneNotSupportedException) cause);
58                } else {
59                    throw new Error("Unexpected exception", cause);
60                }
61            } catch (IllegalAccessException ex) {
62                throw new IllegalAccessError(ex.getMessage());
63            }
64        } else {
65            throw new CloneNotSupportedException();
66        }
67    }
68
69    /**
70     * This class should not be instantiated.
71     */
72    private CloneUtils() {
73    }
74
75}
76