1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
29
30
31
32
33 public class CloningProvider implements ObjectProvider
34 {
35 private final Cloneable cloneable;
36 private Method cloneMethod;
37
38
39
40
41
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 }