001/* 002 * Copyright 2002-2017 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.lang.Nullable; 022import org.springframework.util.ClassUtils; 023import org.springframework.util.StringUtils; 024 025/** 026 * Property editor for {@link Class java.lang.Class}, to enable the direct 027 * population of a {@code Class} property without recourse to having to use a 028 * String class name property as bridge. 029 * 030 * <p>Also supports "java.lang.String[]"-style array class names, in contrast to the 031 * standard {@link Class#forName(String)} method. 032 * 033 * @author Juergen Hoeller 034 * @author Rick Evans 035 * @since 13.05.2003 036 * @see Class#forName 037 * @see org.springframework.util.ClassUtils#forName(String, ClassLoader) 038 */ 039public class ClassEditor extends PropertyEditorSupport { 040 041 @Nullable 042 private final ClassLoader classLoader; 043 044 045 /** 046 * Create a default ClassEditor, using the thread context ClassLoader. 047 */ 048 public ClassEditor() { 049 this(null); 050 } 051 052 /** 053 * Create a default ClassEditor, using the given ClassLoader. 054 * @param classLoader the ClassLoader to use 055 * (or {@code null} for the thread context ClassLoader) 056 */ 057 public ClassEditor(@Nullable ClassLoader classLoader) { 058 this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader()); 059 } 060 061 062 @Override 063 public void setAsText(String text) throws IllegalArgumentException { 064 if (StringUtils.hasText(text)) { 065 setValue(ClassUtils.resolveClassName(text.trim(), this.classLoader)); 066 } 067 else { 068 setValue(null); 069 } 070 } 071 072 @Override 073 public String getAsText() { 074 Class<?> clazz = (Class<?>) getValue(); 075 if (clazz != null) { 076 return ClassUtils.getQualifiedName(clazz); 077 } 078 else { 079 return ""; 080 } 081 } 082 083}