01: /*
02: * Copyright 2004-2007 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 org.springframework.binding.convert.support;
17:
18: import org.springframework.binding.convert.ConversionContext;
19: import org.springframework.util.Assert;
20: import org.springframework.util.ClassUtils;
21: import org.springframework.util.StringUtils;
22:
23: /**
24: * Converts a textual representation of a class object to a <code>Class</code>
25: * instance.
26: *
27: * @author Keith Donald
28: */
29: public class TextToClass extends ConversionServiceAwareConverter {
30:
31: private static final String ALIAS_PREFIX = "type:";
32:
33: private static final String CLASS_PREFIX = "class:";
34:
35: public Class[] getSourceClasses() {
36: return new Class[] { String.class };
37: }
38:
39: public Class[] getTargetClasses() {
40: return new Class[] { Class.class };
41: }
42:
43: protected Object doConvert(Object source, Class targetClass,
44: ConversionContext context) throws Exception {
45: String text = (String) source;
46: if (StringUtils.hasText(text)) {
47: String classNameOrAlias = text.trim();
48: if (classNameOrAlias.startsWith(CLASS_PREFIX)) {
49: return ClassUtils.forName(text.substring(CLASS_PREFIX
50: .length()));
51: } else if (classNameOrAlias.startsWith(ALIAS_PREFIX)) {
52: String alias = text.substring(ALIAS_PREFIX.length());
53: Class clazz = getConversionService().getClassByAlias(
54: alias);
55: Assert.notNull(clazz,
56: "No class found associated with type alias '"
57: + alias + "'");
58: return clazz;
59: } else {
60: // try first an aliased based lookup
61: if (getConversionService() != null) {
62: Class aliasedClass = getConversionService()
63: .getClassByAlias(classNameOrAlias);
64: if (aliasedClass != null) {
65: return aliasedClass;
66: }
67: }
68: // treat as a class name
69: return ClassUtils.forName(classNameOrAlias);
70: }
71: } else {
72: return null;
73: }
74: }
75: }
|