View Javadoc
1   /*
2    * Copyright 2005 Philipp Erlacher
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5    * in compliance with the License. You may obtain a copy of the License at
6    *
7    * http://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software distributed under the License
10   * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11   * or implied. See the License for the specific language governing permissions and limitations under
12   * the License.
13   */
14  package org.exolab.castor.xml.parsing.primitive.objects;
15  
16  import java.lang.reflect.InvocationTargetException;
17  import java.lang.reflect.Method;
18  
19  import org.apache.commons.lang3.StringUtils;
20  
21  /**
22   * This class is part of the command pattern implementation to instantiate an object. It is used as
23   * a command by the command invoker {@link PrimitiveObject}.
24   * 
25   * @author <a href="mailto:philipp DOT erlacher AT gmail DOT com">Philipp Erlacher</a>
26   * 
27   */
28  class PrimitiveEnum extends PrimitiveObject {
29  
30    @Override
31    public Object getObject(Class<?> type, String value) {
32      if (StringUtils.isEmpty(value)) {
33        return null;
34      }
35  
36      // discover the fromValue Method
37      try {
38        Method valueOfMethod = type.getMethod("fromValue", new Class[] {String.class});
39        return valueOfMethod.invoke(null, new Object[] {value});
40  
41      } catch (NoSuchMethodException e) {
42        // do nothing, check valueOf method
43      } catch (IllegalArgumentException e) {
44        throw new IllegalStateException(e.toString());
45      } catch (IllegalAccessException e) {
46        throw new IllegalStateException(e.toString());
47      } catch (InvocationTargetException e) {
48        if (e.getTargetException() instanceof RuntimeException) {
49          throw (RuntimeException) e.getTargetException();
50        }
51      }
52  
53      // backwards compability, check valueOf method to support
54      // "simple" enums without value object
55      try {
56        Method valueOfMethod = type.getMethod("valueOf", new Class[] {String.class});
57        return valueOfMethod.invoke(null, new Object[] {value});
58  
59      } catch (IllegalAccessException e) {
60        throw new IllegalStateException(e.toString());
61      } catch (InvocationTargetException e) {
62        if (e.getTargetException() instanceof RuntimeException) {
63          throw (RuntimeException) e.getTargetException();
64        }
65      } catch (NoSuchMethodException e) {
66        String err = type.getName() + " does not contain the required method: public static "
67            + type.getName() + " valueOf(String);";
68        throw new IllegalArgumentException(err);
69      }
70  
71      return value;
72    }
73  
74  }