Last active
September 12, 2017 08:02
-
-
Save subchen/1d2b5b9b1bb5d912341427f27050ad41 to your computer and use it in GitHub Desktop.
issue fix
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@SuppressWarnings("unchecked") | |
private <T> T stringAsObject(String value, Class<T> targetClass, String defaultValue) { | |
value = StringUtils.trimToNull(value); | |
if (value == null) { | |
value = defaultValue; | |
} | |
if (value == null || value.length() == 0) { | |
return null; | |
} | |
value = resolve(value); | |
if (targetClass == String.class) { | |
return (T) value; | |
} | |
if (value.startsWith("$")) { | |
// this is a reference name | |
return aliasNameAsObject(value, targetClass, null); | |
} | |
if (targetClass == Object.class) { | |
return aliasNameAsObject(value, targetClass, null); | |
} | |
if (TypeCastUtils.support(targetClass)) { | |
return TypeCastUtils.convert(value, targetClass); | |
} | |
if (ClassUtils.available(value)) { | |
// this is a class name | |
return aliasNameAsObject(value, targetClass, null); | |
} | |
ClassLoader loader = getClass().getClassLoader(); | |
if (ClassUtils.available(value, loader)) { | |
return aliasNameAsObject(value, targetClass, loader); | |
} | |
throw new IllegalStateException("Cannot convert to " + targetClass + " from `" + value + "`"); | |
} | |
protected <T> T aliasNameAsObject(String aliasName, Class<T> targetClass, ClassLoader loader) { | |
// 1. get class name and props | |
String className; | |
Set<String> propNames; | |
if (aliasName.startsWith("$")) { | |
// this is a reference name | |
className = doGetValue(aliasName, String.class, null); | |
propNames = keySet(aliasName.concat(".")); | |
} else { | |
// this is a class name | |
className = aliasName; | |
propNames = null; | |
} | |
// 2. load class | |
Class<?> cls; | |
try { | |
cls = ClassLoaderUtils.loadClassEx(className, loader); | |
} catch (ClassNotFoundException e) { | |
throw new IllegalStateException(e); | |
} | |
if (!targetClass.isAssignableFrom(cls)) { | |
throw new IllegalStateException("cannot convert `" + className + "` to " + targetClass); | |
} | |
// 3. create instance | |
return newInstance(aliasName, cls, propNames); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment