EnumPropertyEditor.java
01 /*
02  * Copyright 2008-2017 the original author or authors.
03  *
04  * Licensed under the Apache License, Version 2.0 (the "License");
05  * you may not use this file except in compliance with the License.
06  * You may obtain a copy of the License at
07  *
08  *     http://www.apache.org/licenses/LICENSE-2.0
09  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package griffon.core.editors;
17 
18 import static griffon.util.GriffonNameUtils.isBlank;
19 
20 /**
21  @author Andres Almiray
22  @since 2.0.0
23  */
24 @SuppressWarnings("rawtypes")
25 public class EnumPropertyEditor extends AbstractPropertyEditor {
26     private Class<? extends Enum> enumType;
27 
28     public Class<? extends Enum> getEnumType() {
29         return enumType;
30     }
31 
32     public void setEnumType(Class<? extends Enum> enumType) {
33         this.enumType = enumType;
34     }
35 
36     @Override
37     protected void setValueInternal(Object value) {
38         if (null == value) {
39             super.setValueInternal(null);
40         else if (value instanceof CharSequence) {
41             handleAsString(String.valueOf(value));
42         else if (value instanceof Enum) {
43             handleAsString(value.toString());
44         else {
45             throw illegalValue(value, enumType);
46         }
47     }
48 
49     @SuppressWarnings("unchecked")
50     protected void handleAsString(String str) {
51         if (isBlank(str)) {
52             super.setValueInternal(null);
53             return;
54         }
55 
56         try {
57             super.setValueInternal(Enum.valueOf(enumType, str));
58         catch (Exception e) {
59             throw illegalValue(str, enumType, e);
60         }
61     }
62 }