| 
01 /*02  * Copyright 2008-2015 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     protected void setValueInternal(Object value) {
 37         if (null == value) {
 38             super.setValueInternal(null);
 39         } else if (value instanceof CharSequence) {
 40             handleAsString(String.valueOf(value));
 41         } else if (value instanceof Enum) {
 42             handleAsString(value.toString());
 43         } else {
 44             throw illegalValue(value, enumType);
 45         }
 46     }
 47
 48     @SuppressWarnings("unchecked")
 49     private void handleAsString(String str) {
 50         if (isBlank(str)) {
 51             super.setValueInternal(null);
 52             return;
 53         }
 54
 55         try {
 56             super.setValueInternal(Enum.valueOf(enumType, str));
 57         } catch (Exception e) {
 58             throw illegalValue(str, enumType, e);
 59         }
 60     }
 61 }
 |