01 /*
02 * Copyright 2008-2014 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 org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
20
21 import javax.annotation.Nonnull;
22 import java.beans.PropertyEditor;
23 import java.beans.PropertyEditorManager;
24 import java.beans.PropertyEditorSupport;
25
26 import static java.util.Objects.requireNonNull;
27
28 /**
29 * The PropertyEditorResolver can be used to locate a property editor for
30 * any given type name. This property editor must support the
31 * java.beans.PropertyEditor interface for editing a given object.
32 * <p/>
33 *
34 * @author Andres Almiray
35 * @since 2.0.0
36 */
37 public final class PropertyEditorResolver {
38 private static final Logger LOG = LoggerFactory.getLogger(PropertyEditorResolver.class);
39
40 private PropertyEditorResolver() {
41
42 }
43
44 /**
45 * Locate a value editor for a given target type.
46 * <p/>
47 * If the input {@code type} is an Enum then an instance of {@code EnumPropertyEditor}
48 * is returned with the {@code type} set as {@code enumType}.
49 *
50 * @param type The Class object for the type to be edited
51 * @return An editor object for the given target class.
52 * The result is null if no suitable editor can be found.
53 * @see griffon.core.editors.EnumPropertyEditor
54 */
55 @Nonnull
56 @SuppressWarnings("unchecked")
57 public static PropertyEditor findEditor(@Nonnull Class<?> type) {
58 requireNonNull(type, "Argument 'type' must not be null");
59 LOG.trace("Searching PropertyEditor for {}", type.getName());
60
61 PropertyEditor editor;
62 if (Enum.class.isAssignableFrom(type)) {
63 editor = new EnumPropertyEditor();
64 ((EnumPropertyEditor) editor).setEnumType((Class<? extends Enum<?>>) type);
65 } else {
66 editor = PropertyEditorManager.findEditor(type);
67 }
68
69 if (editor == null) {
70 editor = new NoopPropertyEditor();
71 }
72
73 LOG.trace("PropertyEditor for {} is {}", type.getName(), editor.getClass().getName());
74 return editor;
75 }
76
77 private static final class NoopPropertyEditor extends PropertyEditorSupport {
78
79 }
80 }
|