1
2
3
4
5
6
7
8
9 package ca.uhn.cache.internal.spring;
10
11 import java.beans.PropertyEditorSupport;
12 import java.lang.reflect.InvocationTargetException;
13 import java.lang.reflect.Method;
14
15 /***
16 * PropertyEditor for org.apache.commons.lang.enum.Enum.
17 *
18 * @author <a href="mailto:alexei.guevara@uhn.on.ca">Alexei Guevara</a>
19 * @author <a href="mailto:tadatoshi.takahashi@uhn.on.ca">Tadatoshi Takahashi (Ken)</a>
20 *
21 * @version $Revision: 1.1 $ updated on $Date: 2005/01/24 22:54:34 $ by $Author: bryan_tripp $
22 */
23 public class CustomEnumEditor extends PropertyEditorSupport {
24
25 private final Class myEnumClazz;
26
27 /***
28 * Create a new CustomEnumEditor instance, using the given Enum class.
29 *
30 * @param theEnumClazz Enum class used to create the Type Safe Enum instance.
31 */
32 public CustomEnumEditor( Class theEnumClazz ) {
33 myEnumClazz = theEnumClazz;
34 }
35
36 /***
37 * Create a new CustomEnumEditor instance, using the given Enum class name.
38 * @param theClassName the name of the <code>Class</code>.
39 * @throws ClassNotFoundException thrown when matching <code>Class</code> is not found.
40 */
41 public CustomEnumEditor( String theClassName ) throws ClassNotFoundException {
42 myEnumClazz = Class.forName( theClassName );
43 }
44
45 /***
46 * @see PropertyEditorSupport#setAsText(java.lang.String)
47 */
48 public void setAsText(String theText) throws IllegalArgumentException {
49 if (theText == null) {
50 throw new IllegalArgumentException( "The empty value is not allowed" );
51 }
52
53 try {
54 Method method = myEnumClazz.getMethod( "getEnum", new Class[ ] { String.class } );
55 Object object = method.invoke( null, new Object[ ] { theText } );
56 if ( object != null ) {
57 setValue( object );
58 }
59 else {
60 throw new IllegalArgumentException( "The name of the Enum " + theText + " doesn't exist. " );
61 }
62 }
63 catch (SecurityException e) {
64 throw new IllegalArgumentException("getEum method is not defined properly, "
65 + "Please provide public getEnum( String theName )." );
66 } catch (NoSuchMethodException e) {
67 throw new IllegalArgumentException("getEnum method is not found, "
68 + "Please provide public getEnum( String theName ).");
69 } catch (IllegalAccessException e) {
70 throw new IllegalArgumentException("getEnum method is not found, "
71 + "Please provide public getEnum( String theName ).");
72 } catch (InvocationTargetException e) {
73 throw new IllegalArgumentException("Invocation of getEnum method failed, "
74 + e.getMessage( ) );
75 }
76 }
77
78 /***
79 * @see PropertyEditorSupport#getAsText()
80 */
81 public String getAsText() {
82
83 return getValue().toString();
84
85 }
86
87 }