1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 package org.apache.commons.proxy.provider;
19
20 import org.apache.commons.proxy.ObjectProvider;
21 import org.apache.commons.proxy.ProxyUtils;
22 import org.apache.commons.proxy.exception.ObjectProviderException;
23
24 import java.lang.reflect.InvocationTargetException;
25 import java.lang.reflect.Method;
26
27 /**
28 * Merely calls <code>clone()</code> (reflectively) on the given {@link Cloneable} object.
29 *
30 * @author James Carman
31 * @since 1.0
32 */
33 public class CloningProvider implements ObjectProvider
34 {
35 private final Cloneable cloneable;
36 private Method cloneMethod;
37
38 /**
39 * Constructs a provider which returns clone copies of the specified {@link Cloneable}
40 * object.
41 * @param cloneable the object to clone
42 */
43 public CloningProvider( Cloneable cloneable )
44 {
45 this.cloneable = cloneable;
46 }
47
48 private synchronized Method getCloneMethod()
49 {
50 if( cloneMethod == null )
51 {
52 try
53 {
54 cloneMethod = cloneable.getClass().getMethod( "clone", ProxyUtils.EMPTY_ARGUMENT_TYPES );
55 }
56 catch( NoSuchMethodException e )
57 {
58 throw new ObjectProviderException(
59 "Class " + cloneable.getClass().getName() + " does not have a public clone() method." );
60 }
61 }
62 return cloneMethod;
63 }
64
65 public Object getObject()
66 {
67 try
68 {
69 return getCloneMethod().invoke( cloneable, ProxyUtils.EMPTY_ARGUMENTS );
70 }
71 catch( IllegalAccessException e )
72 {
73 throw new ObjectProviderException(
74 "Class " + cloneable.getClass().getName() + " does not have a public clone() method.", e );
75 }
76 catch( InvocationTargetException e )
77 {
78 throw new ObjectProviderException(
79 "Attempt to clone object of type " + cloneable.getClass().getName() + " threw an exception.", e );
80 }
81 }
82
83 }