1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38 package com.gargoylesoftware.base.objectstore;
39
40 import com.gargoylesoftware.base.util.DetailedIllegalArgumentException;
41 import java.lang.reflect.InvocationTargetException;
42 import java.lang.reflect.Method;
43 import java.util.HashMap;
44 import java.util.Map;
45
46 /***
47 * An object store that allows configuration by reflection. Commands are mapped to
48 * method names such that when a specified command is received, it will be dispatched
49 * via reflection to the specified method.
50 *
51 * @version $Revision: 1.4 $
52 * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
53 */
54 public abstract class ReflectedObjectStore extends ObjectStore {
55
56 private final Map commandMap_ = new HashMap( 89 );
57
58
59 /***
60 * Create an instance
61 */
62 public ReflectedObjectStore() {
63 }
64
65
66 /***
67 * Execute the specified command
68 *
69 * @param command The command to execute
70 * @return An object
71 * @exception Throwable If an error occurs
72 */
73 protected final Object executeImpl( final ObjectStoreCommand command )
74 throws Throwable {
75
76 final Method method = (Method)commandMap_.get( command.getClass() );
77 if( method == null ) {
78 throw new ObjectStoreCommandNotSupportedException( command );
79 }
80
81 try {
82 return method.invoke( this, new Object[]{command} );
83 }
84 catch( final InvocationTargetException e ) {
85 throw e.getTargetException();
86 }
87 }
88
89
90 /***
91 * Register a command and the method that will be invoked when that command is
92 * passed into execute()
93 *
94 * @param commandClass The class of the command
95 * @param methodName The name of the method that will be executed
96 */
97 public void registerCommand( final Class commandClass, final String methodName ) {
98 assertNotNull( "commandClass", commandClass );
99 assertNotNull( "methodName", methodName );
100
101 if( ObjectStoreCommand.class.isAssignableFrom( commandClass ) == false ) {
102 throw new DetailedIllegalArgumentException(
103 "commandClass", commandClass, "Must be an instance of ObjectStoreCommand" );
104 }
105
106 final Method method;
107 try {
108 method = getClass().getDeclaredMethod( methodName, new Class[]{commandClass} );
109 }
110 catch( final NoSuchMethodException e ) {
111 throw new DetailedIllegalArgumentException(
112 "methodName", methodName, "No method found on class " + commandClass.getName() );
113 }
114
115 attemptToSuppressAccessControl( method );
116
117 commandMap_.put( commandClass, method );
118 }
119
120
121 private void attemptToSuppressAccessControl( final Method method ) {
122 try {
123 method.setAccessible( true );
124 }
125 catch( final SecurityException e ) {
126
127 }
128 }
129 }
130