001/*
002 * Copyright 2002-2012 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.beans.propertyeditors;
018
019import java.beans.PropertyEditorSupport;
020
021import org.springframework.util.ClassUtils;
022import org.springframework.util.StringUtils;
023
024/**
025 * Property editor for {@link Class java.lang.Class}, to enable the direct
026 * population of a {@code Class} property without recourse to having to use a
027 * String class name property as bridge.
028 *
029 * <p>Also supports "java.lang.String[]"-style array class names, in contrast to the
030 * standard {@link Class#forName(String)} method.
031 *
032 * @author Juergen Hoeller
033 * @author Rick Evans
034 * @since 13.05.2003
035 * @see Class#forName
036 * @see org.springframework.util.ClassUtils#forName(String, ClassLoader)
037 */
038public class ClassEditor extends PropertyEditorSupport {
039
040        private final ClassLoader classLoader;
041
042
043        /**
044         * Create a default ClassEditor, using the thread context ClassLoader.
045         */
046        public ClassEditor() {
047                this(null);
048        }
049
050        /**
051         * Create a default ClassEditor, using the given ClassLoader.
052         * @param classLoader the ClassLoader to use
053         * (or {@code null} for the thread context ClassLoader)
054         */
055        public ClassEditor(ClassLoader classLoader) {
056                this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());
057        }
058
059
060        @Override
061        public void setAsText(String text) throws IllegalArgumentException {
062                if (StringUtils.hasText(text)) {
063                        setValue(ClassUtils.resolveClassName(text.trim(), this.classLoader));
064                }
065                else {
066                        setValue(null);
067                }
068        }
069
070        @Override
071        public String getAsText() {
072                Class<?> clazz = (Class<?>) getValue();
073                if (clazz != null) {
074                        return ClassUtils.getQualifiedName(clazz);
075                }
076                else {
077                        return "";
078                }
079        }
080
081}